简体   繁体   中英

Find distinct elements from List<List<String>>

I want to find the distinct elements in a nested list based on the values of the inner list.

Current list structure : the following image shows a table where each row is a list of string and the whole table is generated using the list of list of string

表

var eachrow = new List<String>();
var allrow = new List<List<String>>();

//eachrow is populated from db. After a complete row is populated it is added to allrow

//Sample
//eachrow[0] = "no value"
//eachrow[1] = "67" and so on
//allrow[0] = {no value,67,89,0,0,0,67,34}
//allrow[1] = {no value,201,45,102,0,0,47,12} and so on

Now I want to eliminate the duplicate rows in the table. I am not looking for a solution in Javascript. the HTML table is generated only for display purpose for the question.

What I have tried

allrow = allrow.Distinct().ToList();
//Doesnt remove duplicates

Use GroupBy like this:

var result = allrow.GroupBy(c => String.Join(",", c))
                                .Select(c => c.First().ToList()).ToList();

Also you can implement an EqualityComparer class and use it in Distinct method of LINQ. But I think it would be more simple by using GroupBy for this purpose as I mentioned.

Ok so here is similar solution to @S.Akbari and should help you to understand how LINQ-based solution actually works.

var rowMap = new Dictionary<string, List<string>>();

foreach (var row in allrow)
{
    string key = string.Join(",", row);

    if (rowMap.ContainsKey(key) == false)
    {
        rowMap.Add(key, row);
    }
}

var result = rowMap.Values.ToList();

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