2

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.

2
  • 1
    We need more information. What is the other IList? What does Exists mean? Do you mean you want to check if this widget exists in the other IList? Commented Jan 15, 2010 at 20:18
  • Yes so we are basically doing a left join btw two lists, and I want to know when the item is in both lists. Commented Jan 15, 2010 at 20:23

2 Answers 2

3

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 }
Sign up to request clarification or add additional context in comments.

3 Comments

Yea I'm sorry about the vagueness was having a hard time being explicit.
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 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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.