• Linq中Select 和 SelectMany 的区别
  • 发布于 2个月前
  • 531 热度
    0 评论
  • 我怕黑
  • 22 粉丝 70 篇博客
  •   
咨询区
Tarik:
我已经 google 搜索了 Select 和 SelectMany 之间的区别,但我并没有找到合适的答案,我现在急切的需要知道在 Linq to SQL 时两者的区别而不是给我用Array展示...

能否有人帮忙提供 Linq To SQL 的例子吗?


回答区
Mike Two:
SelectMany 它是对 列表中的列表 进行扁平化查询,比如下面的例子。
public class PhoneNumber
{
    public string Number { get; set; }
}

public class Person
{
    public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
    public string Name { 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);

// And to include data from the parent in the result: 
// pass an expression to the second parameter (resultSelector) in the overload:
var directory = people
   .SelectMany(p => p.PhoneNumbers,
               (parent, child) => new { parent.Name, child.Number });
Sriwantha Attanayake:
SelectMany 类似 Sql 中的 cross join ,也就是所谓的笛卡尔积,比如下面的例子。
Set A={a,b,c}
Set B={x,y}
SelectMany 之后会得到如下结果。
{ (x,a) , (x,b) , (x,c) , (y,a) , (y,b) , (y,c) }
可以看出,上面就是罗列了 SetA 和 SetB 的所有组合,转换成 linq 的话可以这么写。
List<string> animals = new List<string>() { "cat", "dog", "donkey" };
List<int> number = new List<int>() { 10, 20 };

var mix = number.SelectMany(num => animals, (n, a) => new { n, a });
输出结果如下:
{(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}
AlejandroR:

var players = db.SoccerTeams.Where(c => c.Country == "Spain")
                            .SelectMany(c => c.players);

foreach(var player in players)
{
    Console.WriteLine(player.LastName);
}
1.De Gea
2.Alba
3.Costa
4.Villa
5.Busquets
点评区
很多时候,我发现越解释概念越说不清楚,最后说着说着就把 理科 变成了 文科,把逻辑变成了硬记😂😂😂,我觉得这时候啥也不要说,直接看源码反而让人更清楚是咋回事。。。
Select 的底层逻辑
// System.Linq.Enumerable
using System.Collections.Generic;

private static IEnumerable<TResult> SelectIterator<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
{
 int index = -1;
 foreach (TSource item in source)
 {
  index = checked(index + 1);
  yield return selector(item, index);
 }
}
SelectMany 的底层逻辑
// System.Linq.Enumerable
using System.Collections.Generic;

private static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>(IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
{
 foreach (TSource element in source)
 {
  foreach (TCollection item in collectionSelector(element))
  {
   yield return resultSelector(element, item);
  }
 }
}
不知道你是否 豁然开朗, 不明白的话,快用 ILSpy 去挖掘 Enumerable 吧!
用户评论