C# 在C中搜索并删除集合中的值

C# 在C中搜索并删除集合中的值,c#,asp.net,asp.net-mvc,c#-4.0,C#,Asp.net,Asp.net Mvc,C# 4.0,我有DetailList.country中的国家列表,如果俄罗斯存在于该集合中,我想将其从该集合中删除。C语言中有内置函数吗 这里的集合是System.Collections.ObjectModel.collection DetailListclass: public class DetailList { public string FirstName { get; set; } public string LastName { get; set; } p

我有DetailList.country中的国家列表,如果俄罗斯存在于该集合中,我想将其从该集合中删除。C语言中有内置函数吗

这里的集合是System.Collections.ObjectModel.collection

DetailListclass:

public class DetailList
    {
public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Country { get; set; }
}

Collection<DetailList> list = new Collection<DetailList>();
总结一下:有几种方法可以用于此

要检查集合中是否存在项,请使用方法。 要从集合中删除项,请使用方法

请注意,即使集合中不存在该项,也可以使用该方法,并且它只会返回false

但是,如果您坚持在删除该项之前检查该项是否确实存在于集合中,我建议使用和,因为它将为您节省对集合的一次搜索

由于我不确定如何阅读您的代码示例,因此我将使用一组字符串来编写此演示代码:

var stringCollection = new Collection<string>();
// Populate here

var index = stringCollection.IndexOf("Russia");
if(index > -1)
{
    stringCollection.RemoveAt(index);
    Console.WriteLine("Russia removed from the collection");
}
else
{
    Console.WriteLine("Russia not found in the collection");
}

你试过输入countrylist吗。然后看看你输入点后自动完成列表中出现了什么?@slugster-是的。但是上下文中没有remove选项。Collection类提供了一个名为remove的方法,正如slugster所指出的,您也应该能够在intellisense中看到它。有关MSDN的文档,请参阅以下链接:@bassfader-首先,我需要检查它是否存在。以及EntityContact类,不确定为什么这里有两个类。为什么不建议使用List?虽然此代码在处理集合时绝对正确,如何为集合实现此功能请参见OP文章中的DetailList类?您需要创建一个DetailList对象,该对象的字段与要删除的字段完全相同。如果您想删除所有包含Country=Russia的项,这对您没有任何帮助。@elloco999据我对文档的理解,在相关对象中覆盖Equals和GetHashCode顺序方法就足够了。@Patrickhoffman在这种情况下,列表优于集合有什么好处?就我所见,两者都实现了我在回答中提到的所有方法。尽管考虑过这个问题,List还是实现了BinarySearch,这是一个与IndexOf对应的Olog n,IndexOf是启用的…@ZoharPeled我试图重写Equals和GetHashCode方法。这确实有效,但需要您用Country=rusia实例化一个新的DetailsList对象。它还有一个令人讨厌的副作用,那就是如果你愿意,就不能再等同于DetailsList对象。