什么是实现最巧妙的方法" MinOrDefault" Linq中? [英] What's the neatest way to achieve "MinOrDefault" in Linq?

查看:143
本文介绍了什么是实现最巧妙的方法" MinOrDefault" Linq中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作从LI​​NQ表达式十进制值的列表,我想最小非零值。然而,它完全有可能的LINQ表达式将导致空列表。



这将引发一个异常,也没有MinOrDefault应付这种局面。



 小数结果=(从项目ITM在ITEMLIST 
,其中itm.Amount大于0
选择itm.Amount)。 MIN();



什么是结果设置为0,如果列表是空的最巧妙的方法?


解决方案

 小数?结果=(从ITEMLIST 
项目ITM,其中itm.Amount = 0
选择(十进制)itm.Amount!?).Min();

请注意转换为小数?。如果有没有( - 我主要说明如何阻止异常只是处理这一事实后),你会得到一个空的结果。我还做了非零用 = ,而不是>!


I'm producing a list of decimal values from a linq expression and I want the minimum non zero value. However it's entirely possible that the linq expression will result in an empty list.

This will raise an exception and there is no MinOrDefault to cope with this situation.

decimal result = (from Item itm in itemList
                  where itm.Amount > 0
                  select itm.Amount).Min();

What's the neatest way to set the result to 0 if the list is empty?

解决方案

decimal? result = (from Item itm in itemList
                  where itm.Amount != 0
                  select (decimal?)itm.Amount).Min();

Note the conversion to decimal?. You'll get an empty result if there are none (just handle that after the fact - I'm mainly illustrating how to stop the exception). I also made "non-zero" use != rather than >.

这篇关于什么是实现最巧妙的方法" MinOrDefault" Linq中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆