fhevol
fhevol

Reputation: 996

C# Create a list of objects from an 2 IEnumerable instances containing only those objects with a value found in the second list

I have 2 different classes:

public class ClassOne
{
    public string ClassOneID { get; set; }
    ...
}

public class ClassTwo
{
    public string ClassTwoID { get; set; }
    ...
}

I have IEnumerable instances of each. I want to return a List<ClassOne> that contains only the ClassOne items whose ClassOneID is equal to the ClassTwoID of a ClassTwo object from the second IEnumerable instance (if that makes sense!). I was thinking the following:

var list = new List<ClassOne>();
list.AddRange(classOneEnumerable.Where(o => 
                classTwoEnumerable.Select(c => c.ClassTwoID == o.ClassOneID).First()));

This logic is contained within code that is some days off building/testing, so I am not actually able to run it just yet. I am not sure if what I have come up with is actually correct, and was hoping someone could put me right if I am mistaken.

Upvotes: 0

Views: 108

Answers (3)

Mike
Mike

Reputation: 3460

The existing answers are fine if you can handle O(n2). Otherwise I would sort the inner values so that you can get n log(n) performance.

Upvotes: 3

Annie Lagang
Annie Lagang

Reputation: 3235

var list = (from classOne in classOneEnumerable
            from classTwo in classTwoEnumerable
            where classOne.ClassOneID == classTwo.ClassTwoID
            select classOne).ToList();

var list2 = (from classOne in classOneEnumerable
             join classTwo in classTwoEnumerable
             on classOne.ClassOneID equals classTwo.ClassTwoID
             select classOne).ToList();

Both queries will yield the same results.

Upvotes: 3

failedprogramming
failedprogramming

Reputation: 2522

Try this

var list = classOneEnumerable.Where(o => classTwoEnumerable
                                  .Any(c => c.ClassTwoID == o.ClassOneID)))
                             .ToList();

Upvotes: 1

Related Questions