我可以将LINQ和foreach用于将对象添加到集合中吗?

时间:2013-08-11 07:13:01

标签: c# linq

我使用以下代码:

IEnumerable<ObjectiveDetail> toBeAdded = 
   objectiveDetail1.Where(a => objectiveDetail2.All(
                          b => b.ObjectiveDetailId != a.ObjectiveDetailId));

然后:

foreach (var _obj in toBeAdded)
{
   _uow.ObjectiveDetails.Add(_obj);
}

这样可以将一个(或多个)新对象详细信息添加到集合中。

但是我很想知道。有没有其他方法可以做到这一点,将LINQ和foreach结合起来?

4 个答案:

答案 0 :(得分:3)

所以你实际上想要添加不在第二个集合中的所有对象。 Enumerable.Except效率更高(假设ObjectiveDetailId是唯一的):

IEnumerable<ObjectiveDetail> toBeAdded = objectiveDetail1.Except(objectiveDetail2);

您需要覆盖Equals + GetHashCode

public class ObjectiveDetail
{
    public int ObjectiveDetailId { get; set; }
    // other properties ...

    public override bool Equals(object obj)
    {
        var obj2 = obj as ObjectiveDetail;
        if (obj2 == null) return false;
        return ObjectiveDetailId == obj2.ObjectiveDetailId;
    }
    public override int GetHashCode()
    {
        return ObjectiveDetailId;
    }
}

顺便说一下,您不需要foreach,可以使用AddRange

_uow.ObjectiveDetails.AddRange(toBeAdded);

答案 1 :(得分:1)

是的,你可以这样做 -

objectiveDetail1.Where(a => objectiveDetail2.All(
                       b => b.ObjectiveDetailId != a.ObjectiveDetailId))
                      .ToList().ForEach(_uow.ObjectiveDetails.Add);

答案 2 :(得分:1)

最短的方法是

_uow.ObjectiveDetails.AddRange(toBeAdded);

答案 3 :(得分:1)

是的。

_uow.ObjectiveDetails.AddRange(
    objectiveDetail1.Where(a => objectiveDetail2.All(
        b => b.ObjectiveDetailId != a.ObjectiveDetailId)));