使用linq

时间:2017-06-15 13:47:04

标签: c# linq

我有一个对象集合

var myData = new[]
{
    new {
        ID = "1285",
        COUNT = 45
    },
    new {
        ID = "1286",
        COUNT = 156
    },
    new {
        ID = "1287",
        COUNT = 965
    }
};

我的另一个收藏来自另一个这样的数据源:

var incomingData = new[]
{
    new {
        ID = "1285",
        LOCATION = "City-1"
    },
    new {
        ID = "1286",
        LOCATION = "City-2"
    },
    new {
        ID = "1287",
        LOCATION = "City-3"
    }
};

我想用ID来改变COUNT属性的传入数据。

var NewData = new[]
{
    new {
        ID = "1285",
        LOCATION = "City-1",
        COUNT = 45
    },
    new {
        ID = "1286",
        LOCATION = "City-2",
        COUNT = 156
    },
    new {
        ID = "1287",
        LOCATION = "City-3",
        COUNT = 965
    }
};

如何使用linq labda函数执行此操作。我不想使用foreach循环。 (myDataincomingData收集长度可能不同)

1 个答案:

答案 0 :(得分:4)

只需使用这样的普通连接语句:

var result= 
    (
        from data in myData
        join inData in incomingData
            on data.ID equals inData.ID
        select new
        {
            data.ID,
            inData.LOCATION,
            data.COUNT
        }
    ).ToList();

简单,简单,易读