如何避免两次使用lambda表达式 [英] How to avoid using lambda expressions twice

查看:93
本文介绍了如何避免两次使用lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我必须调用两次相同的表达式以获得与STRING匹配的First Item。有没有更好的方法呢?



Hi, In code below I have to call same expression twice to get First Item that matches STRING. Is there any better way of doing this?

if (InvoiceDetails.Where(x => x.IMEINumber == boostReconcile.BoostSheetLine.BoostImei).Count() > 0)
                   {
                       boostReconcile.InvoiceDetail = InvoiceDetails.Where(x => x.IMEINumber == boostReconcile.BoostSheetLine.BoostImei).First();
                   }





我尝试过:



没有任何关于代码的描述。



What I have tried:

There is nothing to describe about the code.

推荐答案

如果可以设置 boostReconcile.InvoiceDetail 到默认值( null ,如果它是引用类型),当没有带有匹配IMEINumber的InvoiceDetail时,你可以这样做:

If it's ok to set boostReconcile.InvoiceDetail to its default value (null if it's a reference type) when there is no InvoiceDetail with a matching IMEINumber then you can do this instead:
boostReconcile.InvoiceDetail = InvoiceDetails.FirstOrDefault(x => x.IMEINumber == boostReconcile.BoostSheetLine.BoostImei);





如果只有0或1个InvoiceDetail符合此标准,则应使用SingleOrDefault()代替:



If there should ever be only 0 or 1 InvoiceDetail that matches this criterion, you should use SingleOrDefault() instead:

boostReconcile.InvoiceDetail = InvoiceDetails.SingleOrDefault(x => x.IMEINumber == boostReconcile.BoostSheetLine.BoostImei);


尝试:

Try:
boostReconcile.InvoiceDetail = InvoiceDetails.FirstOrDefault(x => x.IMEINumber == boostReconcile.BoostSheetLine.BoostImei);



Enumerable.FirstOrDefault (TSource)方法(IEnumerable(TSource),Func(TSource,Boolean))(System.Linq) [ ^ ]



注意:如果没有匹配的记录,那将用 null 覆盖该属性。如果您已在该属性中有值,并且您不想覆盖它,请尝试:


Enumerable.FirstOrDefault(TSource) Method (IEnumerable(TSource), Func(TSource, Boolean)) (System.Linq)[^]

NB: That will overwrite the property with null if there are no matching records. If you already have a value in the property, and you don't want to overwrite it, then try:

boostReconcile.InvoiceDetail = InvoiceDetails.FirstOrDefault(x => x.IMEINumber == boostReconcile.BoostSheetLine.BoostImei) ?? boostReconcile.InvoiceDetail;


尝试
var g = InvoiceDetails.Where(x => x.IMEINumber == boostReconcile.BoostSheetLine.BoostImei);
if (g.Count() > 0)
                   {
                       boostReconcile.InvoiceDetail = g.First();
                   }


这篇关于如何避免两次使用lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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