Remove instances from a list by using LINQ or Lambda?

前端 未结 7 1611
囚心锁ツ
囚心锁ツ 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 04:00

    For collections that are not lists (can't expose RemoveAll), you can still remove items with a one-liner.

    To replace inline, just generate a list of items to remove, then run through it and execute remove code.

    var dictionary = new Dictionary(){{"foo", "0"}, {"boo", "1"}, {"goo", "1"}};
    dictionary
        .Where(where_item =>
            ((where_item.Key == "foo") && (where_item.Value == "0"))
            || ((where_item.Key == "boo") && (where_item.Value == "1"))
        )
        .ToList()
        .ForEach(remove_item => {
            dictionary.Remove(remove_item.Key);
        });
    

    To replace in copy, just generate a filtered enumerable and return a new copy.

    var dictionary0 = new Dictionary(){{"foo", "0"}, {"boo", "1"}, {"goo", "1"}};
    var dictionary1 = dictionary0
        .Where(where_item =>
            ((where_item.Key == "foo") && (where_item.Value == "0"))
            || ((where_item.Key == "boo") && (where_item.Value == "1"))
        )
        .ToDictionary(each_item => each_item.Key, each_item => each_item.Value);
    

提交回复
热议问题