当对象属性重复时从对象列表中删除项目
我对 linq 和 c# 相当陌生,所以如果我很愚蠢,我很抱歉。我有一个查询,它根据传入的一些变量返回产品信息、这些产品的价格和这些产品所属的类别的列表:
var y = (from pl in dc.Products
join pr in dc.Prices
on pl.ID equals pr.ProductID
join c in dc.Categories
on pl.ID equals c.ProductID
where pr.Currency == Currency
&& (string.IsNullOrEmpty(Cat1) || c.Cat1 == Cat1)
&& (string.IsNullOrEmpty(Cat2) || c.Cat2 == Cat2)
&& (string.IsNullOrEmpty(Cat3) || c.Cat3 == Cat3)
&& (string.IsNullOrEmpty(Cat4) || c.Cat4 == Cat4)
&& (string.IsNullOrEmpty(Cat5) || c.Cat5 == Cat5)
select new {pl,pr,c});
就其本身而言,这工作得很好,但例如,一行 y 的 ID = 1并且 Cat1 = Foo,另一行的 ID = 1 且 Cat1 = Bar,那么显然上面的查询会将两者都返回。有没有办法修改这个查询,以便我可以为每个 ID 只返回一行。
我已经用 Google 搜索了大约 2 个小时,并尝试了 group bys、.Distinct 和 IEqualityComparer 以及我发现的其他方法,但没有成功。我的理解不够好,我将不胜感激任何帮助!
I am reasonably new to linq and c# so apologies if I am being dumb. I have a query which brings back a list of product info, prices of these products and categories these products are in based on some variables passed in:
var y = (from pl in dc.Products
join pr in dc.Prices
on pl.ID equals pr.ProductID
join c in dc.Categories
on pl.ID equals c.ProductID
where pr.Currency == Currency
&& (string.IsNullOrEmpty(Cat1) || c.Cat1 == Cat1)
&& (string.IsNullOrEmpty(Cat2) || c.Cat2 == Cat2)
&& (string.IsNullOrEmpty(Cat3) || c.Cat3 == Cat3)
&& (string.IsNullOrEmpty(Cat4) || c.Cat4 == Cat4)
&& (string.IsNullOrEmpty(Cat5) || c.Cat5 == Cat5)
select new {pl,pr,c});
This works fine as far as it goes but say for example a row of y has ID = 1 and Cat1 = Foo and another row has ID = 1 and Cat1 = Bar, then obviously the query above will bring both back. Is there a way to modify this query so that I can bring back just one row for each ID.
I've Googled this for about 2 hours and tried group bys, .Distinct with an IEqualityComparer and other methods I found but with no success. My understanding isn't good enough and I'd be grateful for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该通过创建一个 HashSet 来做到这一点,其中键是您的属性。
如果要从原始列表中删除项目,可以使用从末尾开始的 for 循环(不能在 for 循环中从列表中删除项目)。
You should do this by making a HashSet where the key is your property.
If you want to remove the items from the original list you can use a for loop starting at the end (you can not remove items from a list in a for loop).