我有一个包含一些属性和列表的列表。我想根据内部列表的属性选择唯一记录如何使用LINQ实现它 例 列表
{item1 = 1, item2=2,list{a1=l1,a2=l2,a3=l5},item3 =3}
{item1 = 21, item2=21,list{a1=l11,a2=l2,a3=l3},item3 =3}
{item1 = 31, item2=22,list{a1=l12,a2=l2,a3=l3},item3 =3}
{item1 = 41, item2=23,list{a1=l1,a2=l2,a3=l3},item3 =3}
我想选择具有不同属性值“a1”的记录。如果我发现重复值为“a1”,那么我将比较值“a3”!=“l5”
预期结果:
{item1 = 21, item2=21,list{a1=l11,a2=l2,a3=l3},item3 =3}
{item1 = 31, item2=22,list{a1=l12,a2=l2,a3=l3},item3 =3}
{item1 = 41, item2=23,list{a1=l1,a2=l2,a3=l3},item3 =3}
答案 0 :(得分:0)
首先,您要在内部列表a1上进行GroupBy,然后在该分组中选择a3!=“l5”。
List<foo> col = new List<foo>();
List<string> tmp = new List<string> {"l1","l2","l5"};
col.Add(new foo {item1 = 1, item2=2,lst=tmp,item3 =3});
tmp = new List<string> {"l11","l2","l3"};
col.Add(new foo {item1 = 21, item2=21,lst=tmp,item3 =3});
tmp = new List<string> {"l12","l2","l3"};
col.Add(new foo {item1 = 31, item2=22,lst=tmp,item3 =3});
tmp = new List<string> {"l1","l2","l3"};
col.Add(new foo {item1 = 41, item2=23,lst=tmp,item3 =3});
var qry = col.GroupBy(i => i.lst[0]).Select(g => g.Where(j => j.lst[2]!="l5"));
如果你的a3不是“l5”有多个副本,那么你将获得所有这些副本,所以如果不需要,你可能需要过滤其他内容。
答案 1 :(得分:0)
class Log
{
public int DoneByEmpId { get; set; }
public string DoneByEmpName { get; set; }
}
public class Class1
{
static void Range()
{
var array = new List<Log>() {new Log() {DoneByEmpId = 1,DoneByEmpName = "Jon"},
new Log() { DoneByEmpId = 1, DoneByEmpName = "Jon" } ,
new Log() { DoneByEmpId = 2, DoneByEmpName = "Max" },
new Log() { DoneByEmpId = 2, DoneByEmpName = "Max" },
new Log() { DoneByEmpId = 3, DoneByEmpName = "Peter" }};
var ordered =
array.GroupBy(x => x.DoneByEmpId).ToList().Select(x => x.FirstOrDefault()).OrderBy(x => x.DoneByEmpName);
foreach (var item in ordered)
{
Console.WriteLine(item.DoneByEmpName);
}
}
}
结果:
乔恩
最大
彼得