如何在C#Liste项目中使用lastOr Default()? [英] How to use lastOr Default() with c# liste items?

查看:356
本文介绍了如何在C#Liste项目中使用lastOr Default()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hii,


Hii ,


List<mylib.MyRole> lst = mylib.MyRole.GetAccessSupportRoleDetailList(compId);
                    int? Id = lst.Where(m => m.IsForMasterAdmin == isForMasterAdmin && m.CompanyId == compId).LastOrDefault().AccessLevelId;




这就是我要尝试做的...在哪里...我想根据lastordefault括号中的条件选择最后一个值.但它不起作用

您能否也建议我这件事实际上是如何工作的..我的意思是..

lst.where(condition).lastordefault();

或lst.lastordefault(condition)

上面的两件事是完全一样的..在这种类型的场景中我有点困惑..




This is what i am trying to do ... where ... I want to take last value as per the metion condition in lastordefault bracket . but its not working

Can you please also suggest me how this things actually work .. I mean ..

lst.where(condition).lastordefault();

or lst.lastordefault(condition)

are the above two things are work exactly same .. I am bit confuse in this type scenrios ..

推荐答案

List<mylib.MyRole> lst = mylib.MyRole.GetAccessSupportRoleDetailList(compId);
                    int? Id = (lst.Where(m => m.IsForMasterAdmin == isForMasterAdmin && m.CompanyId == compId).AccessLevelId).LastOrDefault();



尝试此操作可能会对您有所帮助.



Try this it may help you.


这不是一件安全的事情:任何引用类型的默认值(我认为是MyRole)是null-所以LastOrDefault如果没有匹配的值,将返回null.
结果,
That''s not a safe thing to do: the default value for any reference type (which I assume MyRole is) is null - so LastOrDefault will return null if there are no matching values.
As a result,
.LastOrDefault().AccessLevelId;

将导致您的程序因空引用异常"而崩溃

在执行方面,两者可能是等效的:Where将返回一个IEnumerable,LastOrDefault的无参数版本将提取该IEnumerable或最后一个值(如果有的话),而带参数的版本则在内部执行Where的等效操作.如果使用参数化版本可能更有效,但是我怀疑那将取决于输入IEnumerable的确切组成.不过,考虑到它们还是要推迟执行查询,因此将是PITA进行性能测试...

我会选择第一个版本-我发现它更容易阅读! :laugh:

will cause your program to crash with an "null reference exception"

In terms of execution, the two are probably equivalent: Where will return an IEnumerable which the parameterless version of LastOrDefault will extract or the last value, if any, and the parameterised version with do the equivalent of the Where internally. If may be slightly more efficient to use the parameterised version, but I suspect that would depend on the exact make up of the input IEnumerable. It''d be a PITA to do performance testing on though, given that they are deferred execution queries anyway...

I''d go with the first version - I find it easier to read! :laugh:


这篇关于如何在C#Liste项目中使用lastOr Default()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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