对此有点新鲜,有没有办法在observablecollection中搜索重复项?基本上这是我的代码:
class Player {
string FirstName;
string SurName;
string Group;
}
private ObservableCollection<MyObj>collection;
基本上玩家可以属于多个组,因此玩家可以多次出现 收集:例如john doe football,john doe baseball,john doe surfing。
我想要实现的是过滤它以显示一个以逗号分隔的组为一组的玩家,如下所示:john doe“football,baseball,surfing”
额外信息:通过执行wcf调用来填充可观察集合(在数据库上执行存储过程并获取结果)
提前致谢
答案 0 :(得分:0)
考虑使用GroupBy运算符进行Linq查询。
答案 1 :(得分:0)
您可以通过查看LAMBDA表达式来完成分组,例如
var grouping = MyCollection.GroupBy(x => new { x.FirstName, x.SurName})
.Select(group => new {group.Key, group});
答案 2 :(得分:0)
首先,我认为你的类是一个公共类,你所有的私有字符串字段(因为它来自你的代码示例)实际上是公共属性(告诉我,如果我错了!)。 所以,你的课程类似于:
public class Player
{
public string FirstName{get; set;}
public string SurName{get; set;}
public string Group{get; set;}
}
内容类似于:
public static ObservableCollection<Player> collection = new ObservableCollection<Player>
{ new Player{FirstName ="Alexander", SurName="Davidof", Group = "Football"},
new Player{FirstName ="Alexander", SurName="Davidof", Group = "Baseball"},
new Player{FirstName ="Alexander", SurName="Medvedev" , Group = "Karate"},
new Player{FirstName ="Alexander", SurName="Medvedev", Group = "Polo"}};
使用LINQ按玩家名称和String.Join()对条目进行分组,将它们连接成单个字符串
var pl = from player in collection
group player by new { First = player.FirstName, Second = player.SurName } into gr
select String.Format("{0} {1} : {2}", gr.Key.First, gr.Key.Second, String.Join(",", gr.Select( a=> a.Group)));
如果您打印此阵列
pl.ToList().ForEach(a => Console.WriteLine(a));
你会看到类似的东西:
Alexander Davidof : Football,Baseball
Alexander Medvedev : Karate,Polo