Reputation: 2134
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
Upvotes: 1
Views: 312
Reputation: 2950
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();
Upvotes: 2
Reputation: 39976
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.
Upvotes: 4