C# 从 IEnumerable<T> 集合中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14143438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:50:48  来源:igfitidea点击:

Remove an item from an IEnumerable<T> collection

c#ienumerable

提问by loyalflow

I have a popuplated IEnumerable<User>collection.

我有一个popuplatedIEnumerable<User>集合。

I want to remove an item from it, how can I do this?

我想从中删除一个项目,我该怎么做?

foreach(var u in users)
{
  if(u.userId = 1123)
  {
    // remove!
  }
}

I know your not suppose to remove while looping, so I don't mind either creating a new collection or removing it after.

我知道您不应该在循环时删除,所以我不介意创建一个新集合或之后删除它。

But I don't know how to remove an item, kind of lost for some reason on this!

但我不知道如何删除一个项目,因为某种原因丢失了!

Alternately which I am confused on also, how can I create a new collection like:

或者我也很困惑,我如何创建一个新的集合,如:

IEnumerable<User> modifiedUsers = new List<User>();

foreach(var u in users)
{
   if(u.userId != 1233)
   {
        modifiedUsers.add ??????
   }
}

How can I add to the collection?

如何添加到集合中?

回答by Tilak

You can't. IEnumerable<T>can only be iterated.

你不能。IEnumerable<T>只能迭代。

In your second example, you can remove from original collection by iterating over a copy of it

在您的第二个示例中,您可以通过迭代它的副本来从原始集合中删除

foreach(var u in users.ToArray()) // ToArray creates a copy
{
   if(u.userId != 1233)
   {
        users.Remove(u);
   }
}

回答by Willem D'Haeseleer

You can not remove an item from an IEnumerable; it can only be enumerated, as described here: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

您不能从IEnumerable; 中删除项目。它只能被枚举,如下所述:http: //msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

You have to use an ICollectionif you want to add and remove items. Maybe you can try and casting your IEnumerable; this will off course only work if the underlying object implements ICollection`.

ICollection如果要添加和删除项目,则必须使用。也许你可以尝试铸造你的IEnumerable; 这当然只有在底层对象实现 ICollection` 时才有效。

See here for more on ICollection: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx

有关更多信息,请参见此处ICollectionhttp: //msdn.microsoft.com/en-us/library/92t2ye13.aspx

You can, of course, just create a new list from your IEnumerable, as pointed out by lante, but this might be "sub optimal", depending on your actual use case, of course.

当然,正如lante 所指出的,您可以从您的IEnumerable 创建一个新列表,但这当然可能是“次优”,这取决于您的实际用例。

ICollectionis probably the way to go.

ICollection可能是要走的路。

回答by dutzu

Try turning the IEnumerableinto a List. From this point on you will be able to use List's Removemethod to remove items.

试着打开IEnumerableList。从现在开始,您将能够使用ListRemove方法来删除项目。

To pass it as a param to the Removemethod using Linq you can get the item by the following methods:

要将其作为参数传递给Remove使用 Linq的方法,您可以通过以下方法获取该项目:

  • users.Single(x => x.userId == 1123)
  • users.First(x => x.userId == 1123)
  • users.Single(x => x.userId == 1123)
  • users.First(x => x.userId == 1123)

The code is as follows:

代码如下:

users = users.ToList(); // Get IEnumerable as List

users.Remove(users.First(x => x.userId == 1123)); // Remove item

// Finished

回答by lante

Not removing but creating a new Listwithout that element with LINQ:

不删除而是List使用 LINQ创建一个没有该元素的新元素:

// remove
users = users.Where(u => u.userId != 123).ToList();

// new list
var modified = users.Where(u => u.userId == 123).ToList();

回答by Charleh

The IEnumerableinterface is just that, enumerable - it doesn't provide any methods to Addor Removeor modify the list at all.

IEnumerable接口就是这样,枚举-它没有提供任何方法AddRemove或全部修改列表。

The interface just provides a way to iterate over some items - most implementations that require enumeration will implement IEnumerablesuch as List<T>

该接口只是提供了一种迭代某些项目的方法 - 大多数需要枚举的实现都会实现,IEnumerable例如List<T>

Why don't you just use your code without the implicit cast to IEnumerable

你为什么不直接使用你的代码而不使用隐式转换 IEnumerable

// Treat this like a list, not an enumerable
List<User> modifiedUsers = new List<User>();

foreach(var u in users)
{
   if(u.userId != 1233)
   {
        // Use List<T>.Add
        modifiedUsers.Add(u);
   }
}

回答by spajce

You can't remove IEnumerable<T>elements, but you can use the Enumerable.Skip Method

您不能删除IEnumerable<T>元素,但可以使用Enumerable.Skip 方法

回答by drovani

There is now an extension method to convert the IEnumerable<>to a Dictionary<,>which then has a Removemethod.

现在有一个扩展方法可以将 the 转换IEnumerable<>为 aDictionary<,>然后有一个Remove方法。

public readonly IEnumerable<User> Users = new User[]; // or however this would be initialized

// To take an item out of the collection
Users.ToDictionary(u => u.Id).Remove(1123);

// To take add an item to the collection
Users.ToList().Add(newuser);

回答by Rafael Mori

You can do something like this:

你可以这样做:

users = users.Where(x => x.userId != userIdToRemove);

回答by Jignesh Gothadiya

users.toList().RemoveAll(user => )

users.toList().RemoveAll(user => )