[英]Check whether a property is unique based on a similar valued property for a list of objects in C#/LINQ
I saw many almost similar scenarios asked, but couldn't find a solution satisfying my need.我看到许多几乎类似的场景被问到,但找不到满足我需求的解决方案。 I have a list of object and in that list, I want to get objects that has similar/duplicate property but with different value for another property in that object.
我有一个对象列表,在该列表中,我想获取具有相似/重复属性但该对象中另一个属性具有不同值的对象。 For instance,
例如,
List<Emp>
: List<Emp>
:
Emp.CubeNo Emp.EmpId
------------------------------
A1 ABC // get this
B1 XYZ
A1 EFG // get this
B2 XXZ
Similar to the case in the above example;类似于上面例子中的情况; assuming each employee has a unique CubeNo, I want to find the CubeNo assigned to multiple employees.
假设每个员工都有一个唯一的 CubeNo,我想找到分配给多个员工的 CubeNo。
I am able to get the result with the following query;我可以通过以下查询获得结果; but I'm sure there is much more elegant way to achieve this.
但我相信有更优雅的方式来实现这一点。 Appreciate all the suggestions..
感谢所有的建议..
var idealList = (from g1 in Emp
join g2 in Emp on g1.CubeNo equals g2.CubeNo
where g1.EmpId != g2.EmpId
select new
{
Property1 = g1.EmpId ,
Property2 = g2.CubeNo
}).ToList();
ListOfObject.GroupBy(x=>x.Property1)
.Where(x=>x.Count()>1)
.Select(x=>x.GroupBy(y=>y.Property2)
.Where(t=>t.Count()==1))
.Where(x=>x.Any())
.SelectMany(x=>x.SelectMany(t=>t))
With sample class i have:使用示例类我有:
public class Class1
{
public string Property1 {get;set;}
public string Property2 {get;set;}
}
var ListOfObject = new List<Class1>
{
new Class1{Property1 = "A1", Property2 = "X1"},
new Class1{Property1 = "B1", Property2 = "Y1"},
new Class1{Property1 = "A1", Property2 = "Z1"},
new Class1{Property1 = "B1", Property2 = "Y1"},
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.