Difference Between Select and SelectMany

来源:互联网 发布:废钞令 知乎 编辑:程序博客网 时间:2024/05/22 12:06

定义:

Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, Int32, TResult>)

Projects each element of a sequence into a new form by incorporating the element's index.

SelectMany<TSource, TResult>(IEnumerable<TSource>, Func<TSource, IEnumerable<TResult>>)

Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.


SelectMany flattens queries that return lists of lists. For example

public class PhoneNumber{    public string Number { get; set; }}public class Person{    public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }}IEnumerable<Person> people = new List<Person>();// Select gets a list of lists of phone numbersIEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);// SelectMany flattens it to just a list of phone numbers.IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);


参考:

http://msdn.microsoft.com/zh-cn/library/system.linq.enumerable(v=vs.100).aspx

http://stackoverflow.com/questions/958949/difference-between-select-and-selectmany

0 0