我有一个具体对象列表。有些需要进行分析以决定将保留哪一个(当该组包含多于1次时)。
以下是一个简化示例:
List<MyObject> arrayObject = new List<MyObject>();
arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat2" });
arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });
这只需要在分析结束时:
arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });
正如您所看到的,带有Cat2的Id2已经消失,因为业务逻辑将其取消了。因此,应该做的是能够获得超过1类别的人并在其上应用逻辑。
以下是我目前的情况:
List<MyObject> arrayObject = new List<MyObject>();
arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat2" });
arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });
var filtered = from arrayObject1 in arrayObject
group arrayObject by new { arrayObject1.Id, arrayObject1.Name }
into g
select new { KKey = g.Key, Obj = g };
foreach(var c in filtered)
{
Console.WriteLine(c.KKey + ":" + c.Obj.Count());
foreach (var cc in c.Obj)
{
//Put some Business Logic here to get only 1... but to simplify will just print
Console.WriteLine("--->" + cc);
}
}
问题是 1)cc不是MyObject类型,其次,我必须通过new获取组中的所有属性...我可能有几个不同的对象。
Linq可以吗?因为,我可以在不使用Linq的情况下做到这一点......但我正在努力尽可能多地应用这个框架的新内容(3.5)。
答案 0 :(得分:4)
问题在于:
group arrayObject by
应该说:
group arrayObject1 by