c# – 如何将Linq var转换为List
发布时间:2020-12-16 00:07:05 所属栏目:百科 来源:网络整理
导读:我试图将 Linq var转换为List.my c#代码是 private ListHyperlinkInfo GetHyperlinkByCode(){ TourInfoBusiness obj = new TourInfoBusiness(); ListHyperlinkInfo lst = new ListHyperlinkInfo(); lst = obj.GetAllHyperlink(); //lst = lst.Select(x = x.A
我试图将
Linq var转换为List.my c#代码是
private List<HyperlinkInfo> GetHyperlinkByCode() { TourInfoBusiness obj = new TourInfoBusiness(); List<HyperlinkInfo> lst = new List<HyperlinkInfo>(); lst = obj.GetAllHyperlink(); //lst = lst.Select(x => x.Attraction).ToList(); var k = lst.Select(x => x.Attraction).Distinct(); } 如果你看上面的代码,直到Line var k = lst.Select(x => x.Attraction).Distinct();现在可以将var k转换为List. 解决方法
根据您的评论,每个Attraction值(字符串)需要单个HyperlinInfo对象.所以,使用分组和ToList():
private List<HyperlinkInfo> GetHyperlinkByCode() { TourInfoBusiness obj = new TourInfoBusiness(); List<HyperlinkInfo> lst = obj.GetAllHyperlink(); return lst.GroupBy(x => x.Attraction) // group links by attraction .Select(g => g.First()) // select first link from each group .ToList(); // convert result to list } 您也可以使用morelinq DistinctBy扩展(可从NuGet获得): private List<HyperlinkInfo> GetHyperlinkByCode() { TourInfoBusiness obj = new TourInfoBusiness(); List<HyperlinkInfo> lst = obj.GetAllHyperlink(); return lst.DistinctBy(x => x.Attraction).ToList(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |