开发者

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
           se开发者_高级运维lect new {Id=w.Id,Label=w.Label,Exists=myWidgets.Contains(w)}

Where my widgets is the second IList.


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 }


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜