c# 4.0 - Verify if two lists share values in C# -


i'd know if 2 lists share values before applying intersection. bool dointersect(lista, listb) fabulous!

this code came with:

// person class id , name properties list<person> people1; list<person> people2;  // populate people1 , people2...  // current solution (pseudocode obviously)...  if (dointersect(people1, people2)) {     people1 = people1.intersect(people2) } else {     /* no shared people */     throw exception; }  // continue process... 

it depends on want:

// there common values between , b? public static bool sharesanyvaluewith<t>(this ienumerable<t> a, ienumerable<t> b) {     return a.intersect(b).any(); } 

for lists don't overlap, iterate through , b each once. lists overlap, iterate way through a, through b until first overlapping element found.

// contain of b? (ignores duplicates) public static bool containsallfrom<t>(this ienumerable<t> a, ienumerable<t> b) {     return !b.except(a).any(); } 

this iterate through once, iterate through b, stopping on first element in b not in a.

// contain of b? (considers duplicates) public static bool containsallfrom<t>(this ienumerable<t> a, ienumerable<t> b) {     // count of each distinct element in     var counts = a.groupby(t => t).todictionary(g => g.key, g => g.count());     foreach (var t in b) {         int count;         // if t isn't in or has few occurrences return false. otherwise, reduce         // count 1         if (!counts.trygetvalue(t, out count) || count == 0) { return false; }         counts[t] = count - 1;     }      return true; } 

similarly, iterate through once, iterate through b, stopping on first element in b not in a.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -