c# - Linq select common subset of nested lists -


i'll begin data structure.

class device {    public list<string> interfaces { get; set; } }  list<device> alldevices; 

i use linq query select interfaces (strings) present in each device in alldevices list.

thanks in adavance.

update: aron managed resolve issue. here's solution:

list<string> commoninterfaces = alldevices.select(device => device.interfaces)    .cast<ienumerable<string>>()    .aggregate(enumerable.intersect)    .tolist(); 

var allinterfaces = device in alldevices                     interface in device.interfaces                     select interface;  var allinterfaces = alldevices.selectmany(device => device.interfaces); 

and if richard dalton correct

var allcommoninterfaces = alldevices               .select(device => device.interfaces.asenumerable())               .aggregate(enumerable.intersect); 

for fun...here more 'optimal' solution.

public static ienumerable<t> commonsubset<t>           (this ienumerable<ienumerable<t>> sequences,             equalitycomparer<t> comparer = null) {     if (sequences == null) throw new argumentnullexception("sequences");       enumerator<t> enumerator = sequences.getenumerator();     if(enumerator.getnext() == false)         throw new argumentexception("sequences must not empty", "sequences");       ienumerable<t> first = enumerator.current;     hashset<t> commonsubset = new hashset<t>(first);     while(enumerator.getnext())     {         var nextsequence = enumerator.current;         var toremove = commonsubset.except(nextsequence, comparer ?? equalitycomparer<t>.default).tolist();         foreach(var r in toremove)             commonsubset.remove(r);     }     return commonsubset; } 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -