使用 C# 泛型根据列的值检索最常见的元素
我有下面的代码从 PetsAgeDataTable 检索最常见的成熟度。我可以使用此代码,但我需要在其他列上执行相同的操作。因此,我需要使其通用并传递 lambda 表达式,以便可以重用它。我只是花了太多时间试图解决这个问题,询问是否有人愿意让我知道如何......干杯/Jan Jensen
var Petmaturity = from p in PetsAgeDataTable
where p.Maturity != null //
group p by new { p.Maturity, p.PetId } into gp
select new { Maturity = gp.Key.Maturity, Count = gp.Coeunt() };
var element= Petmaturity.OrderByDescending(s => s.Count).First()
I have the code below that retrieves the most common maturity from PetsAgeDataTable. I have this code working but I will need to do the same trick on an other column. I therefore need to make it generic and pass a lambda expression so it can be reused. I'm just spending far too much time trying to figure it out there asking if anyone would be kind enough to let me know how... Cheers / Jan Jensen
var Petmaturity = from p in PetsAgeDataTable
where p.Maturity != null //
group p by new { p.Maturity, p.PetId } into gp
select new { Maturity = gp.Key.Maturity, Count = gp.Coeunt() };
var element= Petmaturity.OrderByDescending(s => s.Count).First()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您的方法采用 lambda:
尝试如下操作:
示例使用:
请注意,您需要一个通用返回类型(除非它始终为
int
)。你不能真正返回匿名类型,但你需要返回一些东西。这里我选择了一个元组,但是你有很多选择,这取决于你打算如何使用它。Assuming your method takes a lambda:
Try something like:
Sample use:
Note that you need a generic return type here (unless it's always
int
). You can't really return the anonymous type, but you need to return something. Here I chose a Tuple, but you have many options, depending on how you intend to use it.