views:

672

answers:

2

So I wrote this simple console app to aid in my question asking. What is the proper way to use a lambda expression on line 3 of the method to get the common members. Tried a Join() but couldn't figure out the correct syntax. As follow up... is there a non-LINQ way to do this in one line that I missed?

class Program
{
    static void Main(string[] args)
    {
        List<int> c = new List<int>() { 1, 2, 3 };
        List<int> a = new List<int>() { 5, 3, 2, 4 };
        IEnumerable<int> j = c.Union<int>(a);
        // just show me the Count
        Console.Write(j.ToList<int>().Count.ToString());

    }
}
+15  A: 
Joel Coehoorn
Yeah, good point. How could I not notice it?
Martinho Fernandes
You made a good point about ordering, though- if they are sorted a Zip -variant would be more efficient
Joel Coehoorn
That was my idea when I asked that. Maybe I'll put that into an answer...
Martinho Fernandes
Too late.
Joel Coehoorn
Yes. Intersect. Couldn't think of the right keyword. +1 and answer. Thanks
tyndall
+2  A: 

If you by lambda syntax mean a real LINQ query, it looks like this:

IEnumerable<int> j =
   from cItem in c
   join aitem in a on cItem equals aItem
   select aItem;

A lambda expression is when you use the => operator, like in:

IEnumerable<int> x = a.Select(y => y > 5);

What you have with the Union method really is a non-LINQ way of doing it, but I suppose that you mean a way of doing it without extension methods. There is hardly a one-liner for that. I did something similar using a Dictionary yesterday. You could do like this:

Dictaionary<int, bool> match = new Dictaionary<int, bool>();
foreach (int i in c) match.Add(i, false);
foreach (int i in a) {
   if (match.ContainsKey(i)) {
      match[i] = true;
   }
}
List<int> result = new List<int>();
foreach (KeyValuePair<int,bool> pair in match) {
   if (pair.Value) result.Add(pair.Key);
}
Guffa