gpt4 book ai didi

c# - 在 lambda 中使用变量

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:13 25 4
gpt4 key购买 nike

我正在使用 Linq 过滤一些东西,有时我需要使用反射来获取值。这是示例:

//...
PropertyType[] properties = myType.GetProperties();
var filtered = properties.Where(p=>p.PropertyType==typeof(MyMetaData)
&& ((MyType)p.GetValue(obj)).Name=="name"
&& ((MyType)p.GetValue(obj)).Length==10
).ToList();
//...

在我的示例中,我多次使用 GetValue() 方法。如果我可以使用变量来存储它,有什么办法吗?我认为这将有助于提高性能。

最佳答案

看起来要在 LINQ 中包含一些变量,我们必须使用表达式查询,而不是方法查询,像这样:

var filtered = (from x in properties
let a = (x.PropertyType is MyType) ? (MyType) x.GetValue(obj) : null
where a != null && a.Name == "name" && a.Length == 10).ToList();

我认为这也适用于带有一些Select方法查询:

var filtered = properties.Select(p=> new {p, a = (p.PropertyType is MyType) ? (MyType) p.GetValue(obj) : null})
.Where(x=>x.a != null && x.a.Name == "name" && x.a.Length == 10)
.Select(x=>x.p).ToList();

关于c# - 在 lambda 中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18213466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com