Difference Between Select and SelectMany

定义:

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 numbers
IEnumerable<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

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页