Best way to remove items from a collection

前端 未结 15 2029
天命终不由人
天命终不由人 2020-12-08 05:47

What is the best way to approach removing items from a collection in C#, once the item is known, but not it\'s index. This is one way to do it, but it seems inelegant at be

15条回答
  •  失恋的感觉
    2020-12-08 06:48

    This is my generic solution

    public static IEnumerable Remove(this IEnumerable items, Func match)
        {
            var list = items.ToList();
            for (int idx = 0; idx < list.Count(); idx++)
            {
                if (match(list[idx]))
                {
                    list.RemoveAt(idx);
                    idx--; // the list is 1 item shorter
                }
            }
            return list.AsEnumerable();
        }
    

    It would look much simpler if extension methods support passing by reference ! usage:

    var result = string[]{"mike", "john", "ali"}
    result = result.Remove(x => x.Username == "mike").ToArray();
    Assert.IsTrue(result.Length == 2);
    

    EDIT: ensured that the list looping remains valid even when deleting items by decrementing the index (idx).

提交回复
热议问题