LINQ:如何连接 ObjectCollection 中的嵌套列表
是否可以在不使用 foreach 循环的情况下为以下问题定义 LINQ 语句?
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();
}
}
在写这个问题的时候,我找到了解决问题的方法。我仍然会发布(并回答)这个问题,因为这对我来说是一个真正的麻烦。而且我在这里没有找到合适的现有问题。
再见, 尤文
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,
Juve
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信这个问题可以通过
SelectMany
和Distinct
来解决!第二个变量名称具有误导性。除其他字母外,它将返回一个
"m"
实例,该实例在原始集合中不是唯一的;)I believe this problem can be solved by
SelectMany
andDistinct
!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 ;)如上所述,我自己找到了答案:
我希望这对某人有帮助。
你好,尤文图斯
As stated above, I found the answer myself:
I hope this helpful for somebody.
Ciao, Juve