闽公网安备 35020302035485号
能否有人帮忙提供 Linq To SQL 的例子吗?
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: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// 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 吧!