c# – 如何将其建模为LINQ查询?
发布时间:2020-12-16 01:57:53 所属栏目:百科 来源:网络整理
导读:我有以下课程: public class A{ public string P1 {get;set;} public string P2 {get;set;} public string P3 {get;set;} public string P3 {get;set;}}public class Id{ public string Main {get;set;} public string SubMain {get;set;}} 有一个List我需
我有以下课程:
public class A { public string P1 {get;set;} public string P2 {get;set;} public string P3 {get;set;} public string P3 {get;set;} } public class Id { public string Main {get;set;} public string SubMain {get;set;} } 有一个List我需要返回一个List,列表中包含所有不同的P1 – P2对. 所以如果在列表中我有: P1 = "A" - P2 "B" P1 = "A" - P2 "C" P1 = "B" - P2 "B" P1 = "A" - P2 "B" 我需要返回一个包含3 Id的List,如: Main = "A" - SubMain "B" Main = "A" - SubMain "C" Main = "B" - SubMain "B" 只有一个LINQ查询可以实现这一点吗?我会说是,但我对Select语句不太满意. 提前致谢. 解决方法
实际上你甚至不需要创建元组(我不喜欢它们用于丑陋的项目名称)来选择不同的值 – 匿名类型具有内置的Equals和GetHashCode实现,它们将用于不同的选择:
list.Select(a => new { a.P1,a.P2 }) .Distinct() .Select(x => new Id { Main = x.P1,SubMain = x.P2 }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |