【问题标题】:Need a linq join that also compares properties需要一个也比较属性的 linq join
【发布时间】:2011-07-19 05:36:38
【问题描述】:

我有两个实体列表。想象一下 list1 是远程的,而 list2 是本地的 - list1 是在过去某个时间创建的,而 list2 刚刚生成。

我想比较两个列表,按 .id 进行匹配,并仅比较每个元素的 .flag 属性。在 .flag 属性不同的地方,我想选择较旧的元素,但使用 list2 中的 .flag 属性(新列表)。

下面的示例显示了如何仅选择 list1 中不同的实体。如何从 list1 中选择不同的实体,但使用 list2 实体中的 .flag 属性。

注意:我不想 select new SomeEntity(){} 整个 SomeEntity 类,因为在真正的问题中,我正在使用的类有很多属性。

class SomeEntity
{
    public int id;
    public bool flag;
    public int some_value = -1;
}

// Setup the test
List<SomeEntity> list1 = new List<SomeEntity>();
List<SomeEntity> list2 = new List<SomeEntity>();
for (int i = 0; i < 10; i++ )
{
    list1.Add(new SomeEntity() { id = i, flag = true, some_value = i * 100 });
    list2.Add(new SomeEntity() { id = i, flag = true, });
}
// Toggle some flags
list1[3].flag = false;
list2[7].flag = false;

// Now find the entities that have changed and need updating
var items_to_update = from x in list1
                      join y in list2 on x.id equals y.id
                      where x.flag != y.flag
                      select x;

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您可以在检索到 items_to_update 集合后将其添加到您的代码中:

     foreach (var item in items_to_update)
     {
         item.flag = list2.Where(c => c.id == item.id).SingleOrDefault().flag;
     }
    

    【讨论】:

    • 这就是我要做的——非常感谢。我想这一切都归结为 Ziav 所说的,linq 不是修改实体的工具。我会把它精简到item.flag = list2.Single(c =&gt; c.id == item.id).flag;
    【解决方案2】:

    如何从 list1 中选择不同的实体,但使用 list2 实体中的 .flag 属性。

    我不想选择 new SomeEntity(){}

    表示要在返回前修改list1中的实体。 Linq 不是用于执行此操作的明确工具。

    foreach (var item in  from x in list1
                          join y in list2 on x.id equals y.id
                          where x.flag != y.flag
                          select new {x, y})
    {
        item.x.flag = item.y.flag
        yield return item.x;
    }
    

    【讨论】:

    • 感谢 Ziav - 当您说 linq 是修改值的错误工具时,您是绝对正确的。
    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多