我正在用以下内容填充一个可观察的集合:
var customers = new ObservableCollection<Customer>();
foreach (
var customer in
collListItem.Select(
item =>
new Customer
{
Persona = item["Persona"].ToString(),
CustomerName = item["Title"].ToString()
}))
{
customers.Add(customer);
}
在我用这个集合中的元素填充 WPF 数据网格之前,我想让它成为角色和客户的唯一列表(没有重复的行)。
我尝试使用以下内容:
customers = customers.Distinct();
但是我收到错误:
Cannot convert source type 'System.Collections.Generic.IEnumerable to target type 'System.Collections.ObjectModel.ObservableCollection
是否有我可以使用的 ObservableCollection
的等效项?
最佳答案
因为 Distinct
返回 IEnumerable<T>
,这不是 ObservableCollection
.
如果你想区分ObservableCollection
你应该像这样重新创建它:
customers = new ObservableCollection<Customer>(customers.Distinct());
或者,作为变体,您可以立即修改您的查询和 distinct:
foreach (
var customer in
collListItem.Select(
item =>
new Customer
{
Persona = item["Persona"].ToString(),
CustomerName = item["Title"].ToString()
}).Distinct())
{
customers.Add(customer);
}
关于c# - 如何使 ObservableCollection 中的项目独一无二?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063678/