【发布时间】:2021-08-02 18:44:00
【问题描述】:
我从数据库中得到 listA。我从最终用户上传的文件中获取 listB,然后将其转换为列表中的正确类。对于这个例子,我给你一个来自数据库的列表和一个用户上传的列表。您可以在下面找到这些示例。
我需要检查 listB 是否在 listA 中,但是当我使用 Except 时,我会得到整个列表,因为 Id 不在 listB 中(数据库中的自动编号)。我现在有一个解决方案,但有更好的方法吗?
到目前为止我所做的尝试:
List<CustomerGroup> listC = listA.Except(listB).ToList();
//Returns listA in listC because Id isn't the same
这是我现在正在使用的,但它似乎很多余。
foreach (CustomerGroup itemToCheck in listB)
{
var foundItem = listA.Find(dbItem => dbItem.FirstName== itemToCheck.FirstName &&
dbItem.FamilyName== itemToCheck.FamilyName &&
dbItem.Quantity == itemToCheck.Quantity &&
dbItem.Discount == itemToCheck.Discount);
if(foundItem != null)
{
listA.Remove(foundItem);
listB.Remove(itemToCheck);
}
}
foreach (CustomerGroup itemToCheck in listB)
{
// other code to check here
}
List<CustomerGroup> listA = new List<CustomerGroup>(){
new CustomerGroup {Id = 1, FirstName = "Anna", FamilyName = "Shrek", Quantity = 5, Discount = 10},
new CustomerGroup {Id = 2, FirstName = "Elsa", FamilyName = "Fiona", Quantity = 5, Discount = 10},
new CustomerGroup {Id = 3, FirstName = "Olaf", FamilyName = "Donkey", Quantity = 5, Discount = 10},
new CustomerGroup {Id = 4, FirstName = "Sven", FamilyName = "Dragon", Quantity = 5, Discount = 5},
new CustomerGroup {Id = 5, FirstName = "Kristoff", FamilyName = "Puss", Quantity = 5, Discount = 10},
new CustomerGroup {Id = 6, FirstName = "Sven", FamilyName = "Dragon", Quantity = 10, Discount = 15},
new CustomerGroup {Id = 7, FirstName = "Kristoff", FamilyName = "Puss", Quantity = 10, Discount = 30}
};
List<CustomerGroup> listB = new List<CustomerGroup>(){
new CustomerGroup { FirstName = "Anna", FamilyName = "Shrek", Quantity = 5, Discount = 10},
new CustomerGroup { FirstName = "Elsa", FamilyName = "Fiona", Quantity = 5, Discount = 8},
new CustomerGroup { FirstName = "Sven", FamilyName = "Dragon", Quantity = 5, Discount = 5},
new CustomerGroup { FirstName = "Kristoff", FamilyName = "Puss", Quantity = 5, Discount = 10},
new CustomerGroup { FirstName = "Sven", FamilyName = "Dragon", Quantity = 10, Discount = 15},
new CustomerGroup { FirstName = "Kristoff", FamilyName = "Puss", Quantity = 10, Discount = 30},
new CustomerGroup { FirstName = "Hans", FamilyName = "Farquaad", Quantity = 20, Discount = 40}
};
public class CustomerGroup{
public int Id {get; set;}
public string FirstName {get; set;}
public string FamilyName {get; set;}
public int Quantity{get; set;}
public int Discount {get; set;}
}
【问题讨论】:
-
这能回答你的问题吗? IEnumerable.Except() and a custom comparer
-
@Liam 我确实从那里得到了一些东西,但我对 lambda 命名感到非常困惑