[英]Is it possible to return an anonymous type that matches TElement to TKey in IEnumerable<IGrouping<TKey, TElement>> returned by GroupBy()?
使用 Linq 的GroupBy()
方法,返回IEnumerable<IGrouping<TKey, TElement>>
类型。
此时,我想在方法调用语法中使用Select()
返回一个将TElement
匹配到TKey
的匿名类型。
这是我们在这个问题中使用的数据。
public class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Pet> pets = new List<Pet>
{
new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 },
new Pet { Name="Daisy", Age=4 }
};
我可以通过在下面的methodCallSyntax
中嵌套foreach
来实现我想要的。
var methodCallSyntax = pets.GroupBy(pet => pet.Age, pet => pet.Name);
foreach (var grouping in methodCallSyntax)
{
foreach (var element in grouping)
{
Console.WriteLine($"Key: {grouping.Key}, Element: {element}");
}
}
但我只想使用foreach
一次。
var methodCallSyntax =
pets
.GroupBy(pet => pet.Age, pet => pet.Name)
// .Select(grouping => new {grouping.Key, Element = grouping.});
foreach (var item in methodCallSyntax)
{
Console.WriteLine($"Key: {item.Key}, Element: {item.Element}");
}
但正如您所看到的,我不知道要填写什么Select()
。
我怎样才能做到这一点?
您可以在 GroupBy 之后使用 SelectMany,并在 SelectMany 中使用 Select。
SelectMany 将多维集合转换为单个序列。 内部 Select 将返回一个集合,并且 SelectMany 会将 Select 中的所有这些值转换为单个集合。
var all = pets
.GroupBy(pet => pet.Age, pet => pet.Name)
.SelectMany(group => group
.Select(name => new { key = group.Key, value = name })
);
用法
foreach (var item in all)
{
Console.WriteLine($"Key: {item.key}, Element: {item.value}");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.