LINQ返回分组为匿名类型的数据子集
本文关键字:类型 数据 子集 返回 LINQ | 更新日期: 2023-09-27 18:09:10
我有一个人的列表,我想使用LINQ(查询语法)来获得一个包含所有名字和所有第二个名字的匿名类型。
如果我使用foreach:
var firstNames = new HashSet<string>();
var secondNames = new HashSet<string>();
foreach (Person p in ListOfPersons)
{
firstNames.Add(p.firstName);
secondNames.Add(p.secondName);
}
返回匿名类型的等效且有效的LINQ语句是什么?例如,allNames。FirstNames and allNames.SecondNames.
编辑:当我说高效时,我的意思是它在ListOfPersons上循环一次,就像上面的foreach示例一样。
编辑2:名称必须不同;我把List<>改成了HashSet<>
如果你不想迭代ListOfPersons两次,我在linq中看到它的唯一方法是
var firstNames = new List<string>();
var secondNames = new List<string>();
persons.Aggregate(Tuple.Create(firstNames, secondNames), (tuple, person) =>
{
tuple.Item1.Add(person.firstName);
tuple.Item2.Add(person.secondName);
return tuple;
});
试试这个:
var AnonList = ListOfPersons.Select(x=> new {firstname = x.firstName, secondname = x.secondName});
var nameList = from l in ListOfPersons
select new { FirstName = l.Firstname, Surname = l.Surname};
这个怎么样:
var allNames = new
{
firstNames = new List<string>(),
secondNames = new List<string>()
};
listOfPersons.ForEach( p =>
{
allNames.firstNames.Add( p.firstName );
allNames.secondNames.Add( p.secondName );
} );
与直觉相反,这是最有效的:
var names = new
{
firstNames = ListOfPersons.Select(x => x.firstName).Distinct().ToList(),
secondNames = ListOfPersons.Select(x => x.secondName).Distinct().ToList(),
};
事实证明,由于创建了更多的临时变量,因此在列表上迭代两次比编写方法迭代一次效率更高。我对这类东西做过速度测试,在列表上迭代多次获胜。