Select
和 SelectMany
都是 LINQ 查询方法,但它们之间有一些区别。
Select
方法用于从集合中选择特定的属性或对集合中的元素进行转换,并返回一个新的集合。例如:
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var squaredNumbers = numbers.Select(x => x * x);
// squaredNumbers 的值为 { 1, 4, 9, 16, 25 }
SelectMany
方法用于对集合中的元素进行嵌套操作,并返回一个扁平化的结果集。例如:
var teams = new List<Team>
{
new Team { Name = "Team A", Members = new List<string> { "Alice", "Bob" } },
new Team { Name = "Team B", Members = new List<string> { "Charlie", "David" } }
};
var allMembers = teams.SelectMany(t => t.Members);
// allMembers 的值为 { "Alice", "Bob", "Charlie", "David" }
因此,Select
用于简单的投射和转换操作,而 SelectMany
用于处理嵌套结构并将其扁平化。
实例:
public class Select
{
public Select(params string[] str)
{
str?.ToList()?.ForEach(x => Attrs.Add(x));
}
public List<string> Attrs { get; set; } = new List<string>();
}
void Main()
{
var demoList = new List<Select>();
demoList.Add(new Select("s1", "s2"));
demoList.Add(new Select("s11", "s22"));
demoList.Add(new Select("s111", "s222"));
var firstList = demoList.Select(x => x.Attrs).ToList();
var secondList = demoList.SelectMany(x => x.Attrs).ToList();
}
firstList 结果:select 只是list 集合中的元素返回
secondList 结果:selectMany 把集合中的list集合合并了返回