1

我正在使用以下代码:

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

4 回答 4

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);
于 2013-08-11T07:46:49.087 回答
1

是的,你可以这样做 -

objectiveDetail1.Where(a => objectiveDetail2.All(
                       b => b.ObjectiveDetailId != a.ObjectiveDetailId))
                      .ToList().ForEach(_uow.ObjectiveDetails.Add);
于 2013-08-11T07:15:14.143 回答
1

最短的方法是

_uow.ObjectiveDetails.AddRange(toBeAdded);
于 2013-08-11T07:15:51.543 回答
1

是的。

_uow.ObjectiveDetails.AddRange(
    objectiveDetail1.Where(a => objectiveDetail2.All(
        b => b.ObjectiveDetailId != a.ObjectiveDetailId)));
于 2013-08-11T07:28:29.290 回答