LINQ: How to join nested Lists in an ObjectCollection

半世苍凉 提交于 2020-08-24 10:48:25

问题


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


回答1:


I believe this problem can be solved by SelectMany and Distinct!

var allLetters = myGroups.SelectMany(go => go.letters);
var allUniqueLetters = allLetters.Distinct();

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 ;)




回答2:


As stated above, I found the answer myself:

List<string> allLetters = (from g in myGroups from l in g.letters select l).ToList();
List<string> allDistinctLetters = allLetters.Distinct().ToList();

I hope this helpful for somebody.

Ciao, Juve



来源:https://stackoverflow.com/questions/3263690/linq-how-to-join-nested-lists-in-an-objectcollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!