LINQ:如何在ObjectCollection中加入嵌套列表 [英] LINQ: How to join nested Lists in an ObjectCollection
问题描述
是否可以使用foreach循环为以下问题定义LINQ语句?
is it possible to define a LINQ statement for the following problems WITHOUT using a foreach loop?
public class GroupObject
{
public String name;
public List<String> letters;
public void test()
{
List<GroupObject> myGroups = new List<GroupObject> {
new GroupObject {
name="test1",
letters=new List<String>{"x","y","z"}
},
new GroupObject {
name="test2",
letters=new List<String>{"l","m","n"}
},
new GroupObject {
name="test3",
letters=new List<String>{"m","x","z"}
}
};
// LINQ problem 1: how to get a list of all 9 letters
// List<string> allLetters = (from ...).ToList();
// LINQ problem 2: how to get a list of all 6 DISTINCT letters
// List<string> allDistictLetters = (from ...).ToList();
}
}
在撰写此问题时,我找到了解决问题的方法.我仍然会发布(并回答)这个问题,因为这个问题对我来说真是个麻烦.而且我在这里没有找到合适的现有问题.
While writing this question, I found a solution to the problems. I will still post (and answer) the question, since this one was a real bugger for me. And I did not find a suitable existing question here.
Ciao, 尤文
推荐答案
我相信SelectMany
和Distinct
可以解决此问题!
I believe this problem can be solved by SelectMany
and Distinct
!
var allLetters = myGroups.SelectMany(go => go.letters);
var allUniqueLetters = allLetters.Distinct();
第二个变量名称具有误导性.它将返回除其他字母外的"m"
的一个实例,该实例在原始集合中不是 唯一;)
The second variable name is misleading tho. It will return, among other letters, one instance of "m"
, which was not unique in the original collection ;)
这篇关于LINQ:如何在ObjectCollection中加入嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!