使用Linq从其他集中存在密钥的集合中删除?

时间:2013-09-25 09:51:15

标签: c# linq

使用Linq进行集合减法的正确方法是什么?我有一个8000多个银行的列表,我想根据路由号码删除一部分银行。该部分位于另一个列表中,路由号码是两者的关键属性。这是一个简化:

public class Bank
{
    public string RoutingNumber { get; set; }
    public string Name { get; set; }
}

var removeThese = new List<string>() { "111", "444", "777" };

var banks = new List<Bank>()
{
    new Bank() { RoutingNumber = "111", Name = "First Federal" },
    new Bank() { RoutingNumber = "222", Name = "Second Federal" },
    new Bank() { RoutingNumber = "333", Name = "Third Federal" },
    new Bank() { RoutingNumber = "444", Name = "Fourth Federal" },
    new Bank() { RoutingNumber = "555", Name = "Fifth Federal" },
    new Bank() { RoutingNumber = "666", Name = "Sixth Federal" },
    new Bank() { RoutingNumber = "777", Name = "Seventh Federal" },
    new Bank() { RoutingNumber = "888", Name = "Eight Federal" },
    new Bank() { RoutingNumber = "999", Name = "Ninth Federal" },
};

var query = banks.Remove(banks.Where(x => removeThese.Contains(x.RoutingNumber)));

6 个答案:

答案 0 :(得分:7)

这应该可以解决问题:

var toRemove = banks.Where(x => removeThese.Contains(x.RoutingNumber)).ToList();
var query = banks.RemoveAll(x => toRemove.Contains(x));

第一步是确保在banks更改时,您不必反复重新运行第一个查询。

这也应该有效:

var query = banks.Except(toRemove);

作为你的第二行。

修改

Tim Schmelter指出,要使Except生效,您需要覆盖EqualsGetHashCode

所以你可以像这样实现它:

public override string ToString()
{
   ... any serialization will do, for instance JSON or CSV or XML ...
   ... OR any serialization that identifies the object quickly, such as:
   return "Bank: " + this.RoutingNumber;
}


public override bool Equals(System.Object obj)
{
    return ((obj is Bank) && (this.ToString().Equals(obj.ToString()));
}


public override int GetHashCode()
{
    return this.ToString().GetHashCode();
}

答案 1 :(得分:6)

一般来说,只需拔出你需要的东西而不是删除那些你不需要的东西就可以了。

var query = myList.Where(x => !removeThese.Contains(x.RoutingNumber));

答案 2 :(得分:5)

此类型的过滤通常使用通用LINQ结构:

banks = banks.Where(bank => !removeThese.Contains(bank.RoutingNumber)).ToList();

在这种特定情况下,您还可以使用List<T>.RemoveAll进行就地过滤,这样会更快:

banks.RemoveAll(bank => removeThese.Contains(bank.RoutingNumber));

另外,出于性能原因,如果要删除的路由号码数量很大,您应该考虑将它们放入HashSet<string>

答案 3 :(得分:4)

使用Linq扩展方法WhereToList创建新列表或使用List.RemoveAll,因为它修改了原始列表,因此效率更高:

banks = banks.Where(x => !removeThese.Contains(x.RoutingNumber)).ToList();
banks.RemoveAll(x => removeThese.Contains(x.RoutingNumber));

当然你必须改变条件,因为前者保留了Where离开的内容,后者删除了RemoveAll中的谓词返回的内容。

答案 4 :(得分:2)

您是否尝试过使用RemoveAll()

var query = banks.RemoveAll(p => removeThese.Contains(p.RoutingNumber));

这将删除banksremoveThese中匹配记录所在的query中的任何值。

banks将包含从列表中删除的记录数。

注意:原始变量{{1}}将由此查询直接更新;不需要重新分配。

答案 5 :(得分:1)

您可以使用RemoveAll()

var removedIndexes = banks.RemoveAll(x => removeThese.Contains(x.RoutingNumber));

banks = banks.Where(bank => !removeThese.Contains(bank.RoutingNumber)).ToList();