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

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)));

最佳答案

这应该可以解决问题:

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();
}

关于c# - 使用Linq从集中删除其他集中存在键的地方?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19001608/

10-10 13:51