JoshBerke
JoshBerke

Reputation: 67068

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.

Upvotes: 2

Views: 122

Answers (2)

Lee
Lee

Reputation: 144126

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() });

Upvotes: 1

Sean Devlin
Sean Devlin

Reputation: 1692

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 }

Upvotes: 3

Related Questions