James Cadd James Cadd - 1 year ago 75
C# Question

LINQ: Use .Except() on collections of different types by making them convertible/comparable?

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.

Collection Types:

public class Data
public int ID { get; set; }

public class ViewModel
private Data _data;

public ViewModel(Data data)
_data = data;

Desired usage:

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

// ...

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?

Answer Source

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

where f maps Data to ViewModel. You will need a IEqualityComparer<Data> too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download