基于其他LINQ / LAMBDA更新列表对象

时间:2010-12-23 02:25:58

标签: c#-3.0 lambda linq-to-objects

这是我的两个对象

    public class ObjectHeaderBuffer
    {
       public int DataObjectId { get; set; }
       public string FileName { get; set; }
       public int RowCount { get; set; }
       public string Checksum { get; set; }
       public int ReconTarget { get; set; }
    } 

    public class ObjectHeaderAttribute
    {
       public int DataObjectId { get; set; }
       public int AttributeType { get; set; }
       public int AttributeValue { get; set; }

    }

        var ohBuffer = new List<ObjectHeaderBuffer>();
        var ohAttribute = new List<ObjectHeaderAttribute>();

我想用ohAttribute.AttributeValue更新ohBuffer.ReconTarget,其中ohBuffer.DataObjectId == ohAttribute.DataObjectId

这是什么linq或lambda?

3 个答案:

答案 0 :(得分:4)

您需要迭代ohBuffer中的每个项目并在ohAttribute中查找值。

假设每个缓冲区只有一个属性,这将起作用。

ohBuffer.ForEach(b => b.ReconTarget = ohAttribute
    .SingleOrDefault(a => a.DataObjectId == b.DataObjectId).AttributeValue);

如果查找返回null,您可以合并为新对象并采用默认值

ohBuffer.ForEach(b => b.ReconTarget = 
    (ohAttribute.SingleOrDefault(a => a.DataObjectId == b.DataObjectId) 
         ?? new ObjectHeaderAttribute())
        .AttributeValue);

或者您可以选择null

ohBuffer.ForEach(b => b.ReconTarget = 
    {
        var attribute = ohAttribute
            .SingleOrDefault(a => a.DataObjectId == b.DataObjectId);

        if (attribute == null)
            return null;
        return attribute.AttributeValue;
    });

答案 1 :(得分:1)

我的方式是:

 foreach (var objectHeaderBuffer in ohBuffer)
        {
            var objectHeaderAttribute = (from c in ohAttribute where c.DataObjectId == objectHeaderBuffer.DataObjectId select c).First();
            objectHeaderBuffer.ReconTarget = objectHeaderAttribute.AttributeValue;
        }

答案 2 :(得分:1)

如果你的关系是1:1那么

 foreach (ObjectHeaderBuffer Itemx in ohBuffer)
 {
    ObjectHeaderAttribute Itemy= (from ObjectHeaderAttribute c in ohAttribute where c.DataObjectId == Itemx.DataObjectId select c).FirstOrDefault();
    if(Itemy!=null)
    {
        Itemx .ReconTarget = Itemy.AttributeValue;
    }
  }

或者

foreach (ObjectHeaderBuffer Itemx in ohBuffer)
{
        ObjectHeaderAttribute Itemy= ohAttribute.Where(c=>c.DataObjectId == Itemx .DataObjectId).FirstOrDefault();
        if(Itemy!=null)
        {
            Itemx .ReconTarget = Itemy.AttributeValue;
        }
}