Remove instances from a list by using LINQ or Lambda?

前端 未结 7 1587
囚心锁ツ
囚心锁ツ 2021-02-05 03:26

Now I come a stage to get all my data as a list in cache(objects) and my next thing I have to do is to remove some instances from the list.

Normally, I would do removing

7条回答
  •  独厮守ぢ
    2021-02-05 03:51

    I agree with Jared's suggestion of filtering out certain items, but it looks like a join on Value1 would be a more efficient approach:

    var res = from item1 in list
              join item2 in toBeRemovedList
                on item1.Value1 equals item2.Value1
              where item1.Value2 >= item2.Value2
              select item1;
    

    Update: Apparently I fail at reading comprehension - new approach:

    var removeDict = toBeRemovedList.ToDictionary(i => i.Value1, i => i.Value2);
    list.RemoveAll(item => {
        int itemToRemoveValue2;
        if(removeDict.TryGetValue(item.Value1, out itemToRemoveValue2))
            return item.Value2 < itemToRemoveValue2;
        return false;
    });
    

    Of course, it would be even better if your list to remove could start as a dictionary. Ultimately, we're just trying to make our match on Value1 more efficient.

提交回复
热议问题