c# - how to find members that exist in at least two lists in a list of lists -


i have array of lists:

var stringlists = new list<string>[]  {      new list<string>(){ "a", "b", "c" },     new list<string>(){ "d", "b", "c" },     new list<string>(){ "a", "d", "c" } }; 

i want extract elements common in @ least 2 lists. example, should elements ["a", "b", "c", "d"]. know how find elements common couldn't think of way solve problem.

you use this:

var result = stringlists.selectmany(l => l.distinct())                         .groupby(e => e)                         .where(g => g.count() >= 2)                         .select(g => g.key); 

just fun iterative solutions:

var seen = new hashset<string>(); var current = new hashset<string>(); var result = new hashset<string>(); foreach (var list in stringlists) {     foreach(var element in list)         if(current.add(element) && !seen.add(element))             result.add(element);      current.clear(); } 

or:

var already_seen = new dictionary<string, bool>(); foreach(var list in stringlists)     foreach(var element in list.distinct())          already_seen[element] = already_seen.containskey(element);  var result = already_seen.where(kvp => kvp.value).select(kvp => kvp.key); 

or (inspired tim's answer):

int tmp; var items = new dictionary<string,int>();  foreach(var str in stringlists.selectmany(l => l.distinct())) {     items.trygetvalue(str, out tmp);     items[str] = tmp + 1; }  var result = items.where(kv => kv.value >= 2).select(kv => kv.key); 

Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -