简体   繁体   中英

Can I combine a LINQ and a foreach that I use to add objects to a collection?

I am using the following code:

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

Then:

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

This works and adds the one (or many) new object details to the collection.

However I am wondering. Is there another way that I could do this that would combine the LINQ and the foreach?

So you actually want to add all objects which are not in the second collection. Enumerable.Except is much more efficient(assuming the ObjectiveDetailId is unique):

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

You need to override 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;
    }
}

Btw, you don't need the foreach , you can use AddRange :

_uow.ObjectiveDetails.AddRange(toBeAdded);

Yeah you can do this way -

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

最短的方法是

_uow.ObjectiveDetails.AddRange(toBeAdded);

Yep.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM