LINQ:通过使它们可转换/可比较,对不同类型的集合使用.Except()吗? [英] LINQ: Use .Except() on collections of different types by making them convertible/comparable?
问题描述
给出两个不同类型的列表,是否有可能使这些类型在彼此之间可转换或可相互比较(例如,使用TypeConverter或类似设备),以便LINQ查询可以对其进行比较?我在SO上也看到了其他类似的问题,但没有任何东西指向使类型之间可以转换以解决问题.
Given two lists of different types, is it possible to make those types convertible between or comparable to each other (eg with a TypeConverter or similar) so that a LINQ query can compare them? I've seen other similar questions on SO but nothing that points to making the types convertible between each other to solve the problem.
集合类型:
public class Data
{
public int ID { get; set; }
}
public class ViewModel
{
private Data _data;
public ViewModel(Data data)
{
_data = data;
}
}
所需用法:
public void DoMerge(ObservableCollection<ViewModel> destination, IEnumerable<Data> data)
{
// 1. Find items in data that don't already exist in destination
var newData = destination.Except(data);
// ...
}
这似乎是合乎逻辑的,因为我知道如何将ViewModel的实例与Data的实例进行比较,所以我应该能够提供一些比较逻辑,然后LINQ会将其用于.Except()之类的查询.这可能吗?
It would seem logical that since I know how to compare an instance of ViewModel to an instance of Data I should be able to provide some comparison logic that LINQ would then use for queries like .Except(). Is this possible?
推荐答案
您最好的选择是提供从Data
到ViewModel
的投影,以便您可以说
Your best bet is to provide a projection from Data
to ViewModel
so that you can say
var newData = destination.Except(data.Select(x => f(x)));
其中,f
将Data
映射到ViewModel
.您还将需要IEqualityComparer<Data>
.
where f
maps Data
to ViewModel
. You will need a IEqualityComparer<Data>
too.
这篇关于LINQ:通过使它们可转换/可比较,对不同类型的集合使用.Except()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!