简体   繁体   中英

How to get Distinct elements from a List of List in c#

I have a list of list, where the child list is list of string. The result i am expecting is list of all distinct strings. For eg:

var listoflist = new List<List<string>> { new List<string> { "A", "B", "C" },
                                          new List<string> { "A", "B", "D", "E" } };

For the above list i expecting the output as {"A","B","C","D","E"}

This is the solution that i found , but i dont feels its a efficient solution.Please provide your thougths on this.

var listoflist = new List<List<string>> { new List<string> { "A", "B", "C" },
                                          new List<string> { "A", "B", "D", "E" } };

List<string> distinctList = new List<string>();
listoflist.ForEach(list =>
{
    distinctList.AddRange(list);
});

distinctList = distinctList.Distinct().ToList();

You can use Enumerable.SelectMany to flatten the lists:

var list = listoflist.SelectMany(x => x).Distinct();

If you want to materialize the query and get a List<string> , add ToList() .

Here,

[TestClass]
public class Class1
{
    [TestMethod]
    public void test()
    {
        var listoflist = new List<List<string>>
        {
            new List<string> {"A", "B", "C"},
            new List<string> {"A", "B", "D", "E"}
        };
        var result = listoflist.SelectMany(l=>l).Distinct().ToList();
        Assert.AreEqual(result.Count, 5);
    }
}

Use SelectMany :-

var res = listoflist.SelectMany(x => x).Distinct();

SelectMany will flatten the list from which on which you can apply the Distinct method. It will return IEnumerable<string> . If you want List<string> as output then simply apply a ToList which will materialize the result:-

List<string> distinctList = listoflist.SelectMany(x => x).Distinct().ToList();
listofList.SelectMany().Distinct()

I would use,

var distinctValues= listoflist[0].Concat(listoflist[1]).GroupBy(a=>a).Select(x => x.First());

Here, first will select first record and groupBy will group the same values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM