tags:

views:

145

answers:

4

I have two lists, one which is a subset of the other.

List 1: A, B, C, D, E
List 2: B, D, E

I'd like to end up with a single collection of the superset with items contained in the subset flagged. This seems to be the sort of thing LINQ could do, but I'm not sure of the syntax.

Result: A, false
        B, true
        C, false
        D, true
        E, true
+3  A: 
var list1 = new string[]{ "A", "B", "C", "D", "E" };
var list2 = new string[]{ "B", "D", "E" };
var result =
from a in list1
select new { Value = a, Has = list2.Contains( a ) };

foreach(var item in result ) {
    Console.WriteLine(string.Format("{0}, {1}", item.Value, item.Has);
}
TcKs
+1  A: 
HashSet<char> subset = new HashSet<char>(list2)

var query = list1
  .Select(x => new
  {
    value = x,
    subsetHas = subset.Contains(x) }
  );
David B
+3  A: 
var list1 = new string[] {"A", "B", "C", "D", "E"};
var list2 = new string[] { "B", "D", "E"};

var query = from item1 in list1
            join item2 in list2 on item1 equals item2 into g
      select new { Name = item1, IsFound = g.Count() > 0};
Darren
+1 - Particularly for large lists, a join will be more efficient than scanning list2 for each item. Note that g.Any() is preferred to g.Count() > 0.
dahlbyk
A: 
var list1 = new[] { "A", "B", "C", "D", "E" };
var list2 = new[] { "B", "D", "E" };
var result =
    list1.Intersect(list2)
         .Select(el => new { el, true })
         .Union(list1.Except(list2)
                     .Select(el => new { el, false }));
Joe Chung