如何从C#中的列表中删除项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10018957/
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-09 12:09:42  来源:igfitidea点击:

How to remove item from list in C#?

c#list

提问by Nate Pet

I have a list stored in resultlist as follows:

我在 resultlist 中存储了一个列表,如下所示:

var resultlist = results.ToList();

It looks something like this:

它看起来像这样:

ID FirstName  LastName
-- ---------  --------
1  Bill       Smith
2  John       Wilson
3  Doug       Berg

How do I remove ID 2 from the list?

如何从列表中删除 ID 2?

采纳答案by Wouter de Kort

List<T>has two methods you can use.

List<T>有两种方法可以使用。

RemoveAt(int index)can be used if you know the index of the item. For example:

如果您知道项目的索引,则可以使用RemoveAt(int index)。例如:

resultlist.RemoveAt(1);

Or you can use Remove(T item):

或者您可以使用Remove(T item)

var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);

When you are not sure the item really exists you can use SingleOrDefault. SingleOrDefaultwill return nullif there is no item (Singlewill throw an exception when it can't find the item). Both will throw when there is a duplicate value (two items with the same id).

当您不确定该项目是否真的存在时,您可以使用SingleOrDefault。如果没有项目SingleOrDefault将返回nullSingle当找不到项目时将抛出异常)。当存在重复值(具有相同 的两个项目id)时,两者都会抛出。

var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
    resultList.Remove(itemToRemove);

回答by KeithS

resultList = results.Where(x=>x.Id != 2).ToList();

There's a little Linq helper I like that's easy to implement and can make queries with "where not" conditions a little easier to read:

有一个我喜欢的小 Linq 助手,它很容易实现,并且可以使带有“where not”条件的查询更容易阅读:

public static IEnumerable<T> ExceptWhere<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
    return source.Where(x=>!predicate(x));
}

//usage in above situation
resultList = results.ExceptWhere(x=>x.Id == 2).ToList();

回答by Vlad

... or just resultlist.RemoveAt(1)if you know exactly the index.

...或者只是resultlist.RemoveAt(1)如果您确切地知道索引。

回答by mgnoonan

You don't specify what kind of list, but the generic List can use either the RemoveAt(index)method, or the Remove(obj)method:

您不指定哪种列表,但泛型 List 可以使用RemoveAt(index)方法或Remove(obj)方法:

// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);

// RemoveAt(index)
resultList.RemoveAt(1);

回答by mgnoonan

There is another approach. It uses List.FindIndexand List.RemoveAt.

还有另一种方法。它使用List.FindIndexList.RemoveAt

While I would probablyuse the solution presented by KeithS (just the simple Where/ToList) this approach differs in that it mutatesthe original list object. This can be a good (or a bad) "feature" depending upon expectations.

虽然我可能使用 KeithS 提供的解决方案(只是简单的Where/ ToList),但这种方法的不同之处在于它会改变原始列表对象。根据预期,这可能是一个好的(或坏的)“功能”。

In any case, the FindIndex(coupled with a guard) ensures the RemoveAtwill be correct if there are gaps in the IDs or the ordering is wrong, etc, and using RemoveAt(vs Remove) avoids a secondO(n) search through the list.

在任何情况下,如果 ID 中存在间隙或排序错误等,(与FindIndex守卫结合)RemoveAt将确保正确,并且使用RemoveAt(vs Remove) 可避免在列表中进行第二次O(n) 搜索。

Here is a LINQPadsnippet:

这是一个LINQPad片段:

var list = new List<int> { 1, 3, 2 };
var index = list.FindIndex(i => i == 2); // like Where/Single
if (index >= 0) {   // ensure item found
    list.RemoveAt(index);
}
list.Dump();        // results -> 1, 3

Happy coding.

快乐编码。

回答by Matt

Short answer:
Remove (from list results)

简短回答:
删除(从列表中results

results.RemoveAll(r => r.ID == 2);will remove the item with ID 2in results(in place).

results.RemoveAll(r => r.ID == 2);将删除与该项目ID 2results(在适当位置)。

Filter (without removing from original list results):

过滤器(不从原始列表中删除results):

var filtered = result.Where(f => f.ID != 2);returns all items except the one with ID 2

var filtered = result.Where(f => f.ID != 2);返回除ID 为 2 的项目之外的所有项目

Detailed answer:

详细解答:

I think .RemoveAll()is very flexible, because you can have a list of item IDs which you want to remove - please regard the following example.

我认为.RemoveAll()非常灵活,因为您可以拥有要删除的项目 ID 列表 - 请参考以下示例。

If you have:

如果你有:

class myClass {
    public int ID; public string FirstName; public string LastName;
}

and assigned some values to resultsas follows:

并将一些值分配给results如下:

var results=new List<myClass> {
    new myClass()  { ID=1, FirstName="Bill", LastName="Smith" },
    new myClass()  { ID=2, FirstName="John", LastName="Wilson" },
    new myClass()  { ID=3, FirstName="Doug", LastName="Berg" },
    new myClass()  { ID=4, FirstName="Bill", LastName="Wilson" },
};

Then you can define a list of IDs to remove:

然后您可以定义要删除的 ID 列表:

var removeList = new List<int>() { 2, 3 };

And simply use this to remove them:

只需使用它来删除它们:

results.RemoveAll(r => removeList.Any(a => a==r.ID));

results.RemoveAll(r => removeList.Any(a => a==r.ID));

It will remove the items 2 and 3and keep the items 1 and 4 - as specified by the removeList. Notethat this happens in place, so there is no additional assigment required.

它将删除项目 2 和 3并保留项目 1 和 4 - 如removeList. 请注意,这是就地发生的,因此不需要额外的分配。

Of course, you can also use it on single items like:

当然,您也可以在单个项目上使用它,例如:

results.RemoveAll(r => r.ID==4);

where it will remove Bill with ID 4 in our example.

在我们的示例中,它将删除 ID 为 4 的 Bill。



DotNetFiddle: Run the demo

DotNetFiddle:运行演示

回答by Javier Andres Caicedo

More simplified:

更简化:

resultList.Remove(resultList.Single(x => x.Id == 2));

there is no needing to create a new var object.

无需创建新的 var 对象。

回答by Prabhakaran M

{
    class Program
    {
        public static List<Product> list;
        static void Main(string[] args)
        {

            list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
                 new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
                 new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
                 new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
                 new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};


            Console.WriteLine("Enter ProductID to remove");
            int uno = Convert.ToInt32(Console.ReadLine());
            var itemToRemove = list.Find(r => r.ProductId == uno);
            if (itemToRemove != null)
                list.Remove(itemToRemove);
            Console.WriteLine($"{itemToRemove.ProductId}{itemToRemove.Name}{itemToRemove.Brand}{itemToRemove.Price}{ itemToRemove.Quantity}");
            Console.WriteLine("------------sucessfully Removed---------------");

            var query2 = from x in list select x;
            foreach (var item in query2)
            {
                /*Console.WriteLine(item.ProductId+" "+item.Name+" "+item.Brand+" "+item.Price+" "+item.Quantity );*/
                Console.WriteLine($"{item.ProductId}{item.Name}{item.Brand}{item.Price}{ item.Quantity}");
            }

        }

    }
}