views:

68

answers:

2
+2  Q: 

Linq query help

I have two collections, and need to create a new collection from the two collections.

Assume the following class:

public class Widget
{
   property int Id{get;set;}
   property string Label{get;set;}
}

We have two IList classes. I would like to create an Anonymous type with Id, Label, and Exists

So doing this for Id and Label, I have:

var newCol=from w in widgets
           select new {Id=w.Id,Label=w.Label,Exists=????}

Is there a way in Linq I can determine exists without writing the looping code myself here?

Edit

Exists tells us if the Widget is in the second list. So for example one solution I just thought of was:

var newCol=from w in widgets
           select new {Id=w.Id,Label=w.Label,Exists=myWidgets.Contains(w)}

Where my widgets is the second IList.

+3  A: 

Your question is really vague, but I'm guessing this is what you want:

var newCol = from w in widgets
             select new { Id = w.Id, Label = w.Label, 
                 Exists = others.Contains(o => o.Id == w.Id }
Sean Devlin
Nice !!!!!!!!!!!!!!!!
Hamish Grubijan
Yea I'm sorry about the vagueness was having a hard time being explicit.
JoshBerke
beat me to it. I had to try pretty hard to understand what he was asking. Though I wouldn't bother with the Lambda in the contains method, just do `Contains(w)`
Scott Anderson
@Scott I considered that, but I think it would depend on the Equals and CompareTo methods of his Widget class, which might not work the way he expects if he hasn't overridden/implemented them and if the two collections aren't references to the same object in memory. This way should work regardless.
Sean Devlin
+1  A: 

You can also do this using GroupJoin:

var newCol = widgets.GroupJoin(
    otherWidgets,
    w => w.Id,
    w => w.Id,
    (w, joined) => new { Id = w.Id, Label = w.Label, Exists = joined.Any() });
Lee