How to Join Two Shared Property Lists

Suppose I have two Lists<myObject>, where myObjectconsists of two properties

Id (type Int) and

Value (type Double)

I need to get a list from these two lists, consisting of (anonymous) objects, such as:

Id, [Double value from List 1], [Double value from List 2]

So, if for a given Id both lists contain a value, it should look like this:

12, 21.75, 19.87

If one list does not contain an object with an identifier that is present in another list, the value must be null:

15, null, 22.52

How can i achieve this? Update: I know how I could get such a list, of course, but I'm looking for the most efficient way to do this, preferably using some witty Linq magic.

+4
2

, , . , , :

var enumerable1 = new[]
{
    new {Id = "A", Value = 1.0},
    new {Id = "B", Value = 2.0},
    new {Id = "C", Value = 3.0},
    new {Id = "D", Value = 4.0},
    new {Id = "E", Value = 5.0},
};

var enumerable2 = new[]
{
    new {Id = "A", Value = 6.0},
    new {Id = "NOT PRESENT", Value = 542.23},
    new {Id = "C", Value = 7.0},
    new {Id = "D", Value = 8.0},
    new {Id = "E", Value = 9.0},
};

var result = enumerable1.Join(enumerable2, arg => arg.Id, arg => arg.Id,
    (first, second) => new {Id = first.Id, Value1 = first.Value, Value2 = second.Value});

foreach (var item in result)
    Console.WriteLine("{0}: {1} - {2}", item.Id, item.Value1, item.Value2);
Console.ReadLine();

- :

A: 1 - 6
C: 3 - 7
D: 4 - 8
E: 5 - 9

, null, ( , double , , ).

+6

. Id? , :

var result = from l1 in list1
             join l2 in list2
               on l1.Id equals l2.Id
             select new {l1.Id, Value1 = l1.Value, Value2 = l2.Value};

, . this.

+4

All Articles