简体   繁体   English

c#在不知道索引号的情况下从列表中删除项目

[英]c# remove item from list without knowing index number

I have a list with collection of my object:我有一个包含我的对象集合的列表:

List<MyObj> list = new List<MyObj>();

My function received MyObj as a parameter and i want to remove this object from the list like suggest here: c# remove item from list我的函数接收 MyObj 作为参数,我想从列表中删除这个对象,就像这里的建议: c# remove item from list

    private void remove(MyObj obj)
    {
        var itemToRemove = list.Where(x => x.fileName == obj.fileName);

        if (itemToRemove != null)
            list.Remove(itemToRemove);
    }

Compiler error received:收到编译器错误:

cannot convert from 'System.Collections.Generic.IEnumerable' to 'namespace.MyObj'无法从“System.Collections.Generic.IEnumerable”转换为“namespace.MyObj”

Where() returns an IEnumerable<> Where()返回一个IEnumerable<>

Try this:试试这个:

private void remove(MyObj obj)
{
    var itemToRemove = list.Where(x => x.fileName == obj.fileName);

    if (itemToRemove.Any())
        list.Remove(itemToRemove.First());
}

Better yet, as you're using List<> :更好的是,当您使用List<>

list.RemoveAll(x => x.fileName == obj.fileName);

Edit编辑

Other solutions, that are all equally viable from the comments below.其他解决方案,从下面的评论中都同样可行。 Pick your poison, though selfishly (and perhaps obviously) I prefer the readability and simplicity of the RemoveAll method:选择你的毒药,虽然自私(也许很明显)我更喜欢RemoveAll方法的可读性和简单性:

Knittl:针织:

list = list.Where(x => x.filename != obj.filename).ToList();

Jeroen van Langen :杰伦·范·兰根

var itemToRemove = list.Where(x => x.fileName == obj.fileName).FirstOfDefault(); 
if (itemToRemove != null)
    list.Remove(itemToRemove);

You were mixed up between Where and FirstOrDefault :你在WhereFirstOrDefault之间FirstOrDefault

private void remove(MyObj obj)
{
    var itemToRemove = list.FirstOrDefault(x => x.fileName == obj.fileName);
    if (itemToRemove != null)
        list.Remove(itemToRemove);
}

There is no need for you to implement this method, the remove method of List already performs this operation as expected.不需要你去实现这个方法,List的remove方法已经按预期执行了这个操作。

http://msdn.microsoft.com/en-us/library/cd666k3e.aspx http://msdn.microsoft.com/en-us/library/cd666k3e.aspx

public bool Remove(
    T item
)

You should use RemoveAll method exposed by list to remove all the matching elements -您应该使用列表公开的RemoveAll方法来删除所有匹配的元素 -

private void remove(MyObj obj)
{
    var itemToRemove = list.RemoveAll(x => x.fileName == obj.fileName);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM