开发者

LINQ: How to join nested Lists in an ObjectCollection

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 q开发者_运维百科uestion here.

Ciao, Juve


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜