我试图派生两个ObservableCollections的联合,并且联合中的项目不是唯一的。
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
namespace ObservableCollectionUnion
{
class Program
{
class Option { public string Code; }
static void Main(string[] args)
{
Option[] opts1 = {
new Option { Code = "1" },
new Option { Code = "2" },
};
Option[] opts2 = {
new Option { Code = "2" },
new Option { Code = "3" },
};
ObservableCollection<Option> obsOpts1 = new ObservableCollection<Option>(opts1);
ObservableCollection<Option> obsOpts2 = new ObservableCollection<Option>(opts2);
ObservableCollection<Option> obsOptsBoth = new ObservableCollection<Option>(obsOpts1.Union(obsOpts2));
foreach (Option opt in obsOptsBoth) {
Debug.WriteLine(opt.Code);
}
}
}
}
输出为:
1
2
2
3
我如何获得1,2,3?我尝试传递IComparer或IEqualityComparer,但出现错误
Error CS1929 'ObservableCollection<Program.Option>' does not contain a definition for 'Union' and the best extension method overload 'Queryable.Union<Program.Option>(IQueryable<Program.Option>, IEnumerable<Program.Option>, IEqualityComparer<Program.Option>)' requires a receiver of type 'IQueryable<Program.Option>'
这就是我要处理的事情
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
namespace ObservableCollectionUnion
{
class Program
{
class Option { public string Code; }
class OptionComparer : IEqualityComparer
{
public new bool Equals(object x, object y)
{
return Convert.ToInt32(((Option)x).Code) == Convert.ToInt32(((Option)y).Code);
}
public int GetHashCode(object obj)
{
return ((Option)obj).Code.GetHashCode();
}
}
static void Main(string[] args)
{
Option[] opts1 = {
new Option { Code = "1" },
new Option { Code = "2" },
};
Option[] opts2 = {
new Option { Code = "2" },
new Option { Code = "3" },
};
ObservableCollection<Option> obsOpts1 = new ObservableCollection<Option>(opts1);
ObservableCollection<Option> obsOpts2 = new ObservableCollection<Option>(opts2);
ObservableCollection<Option> obsOptsBoth = new ObservableCollection<Option>(obsOpts1.Union(obsOpts2, new OptionComparer()));
foreach (Option opt in obsOptsBoth) {
Debug.WriteLine(opt.Code);
}
}
}
}
有趣的是,我正在遵循智能感知告诉我的内容。它说ObservableCollection.Union的签名是
public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer);
答案 0 :(得分:1)
它不会返回重复项。如果您做了类似的事情
var commonOption = new Option { Code = "2" }
并将其用于可观察的集合中,它将按预期工作。默认情况下,仅当它们是同一实例时,类才相等。如果需要其他种类的相等性,可以通过覆盖相等性运算符来定义它。