简体   繁体   English

动态Linq FirstOrDefault语句

[英]Dynamic Linq FirstOrDefault Statement

Using C# 7+, I am instantiating a variable via a FirstOrDefault() statement. 使用C#7+,我通过FirstOrDefault()语句实例化一个变量。 But it's repeated throughout the code for different variables. 但是在整个代码中针对不同的变量进行了重复。 I'm wondering if/how I can build these statements dynamically. 我想知道是否/如何动态构建这些语句。 This is what I currently have (notice that the variable name matches the DataTable name) 这是我目前拥有的(注意变量名与DataTable名称匹配)

var generalSolution = this.GeneralSolution.FirstOrDefault();
var pieceModel = this.PieceModel.FirstOrDefault();
.... many more of these same variable declarations.....

What I would like to do is given a list of strings, create each of these variables iteratively. 我想给的是一个字符串列表,迭代地创建每个变量。 Something like: 就像是:

foreach(var item in list)
{
    var somename = this."item".FirstOrDefault();
}

Is this even, at all, possible? 完全有可能吗?

Yes, you can do this with reflection, but it will require some work to get it into an easy to work with format and may not be recommended. 是的,您可以通过反射来完成此操作,但是需要一些工作才能使其易于使用格式,因此可能不建议这样做。

See this dotnetfiddle for a quick example I threw together 请参阅此dotnetfiddle,了解我一起提出的快速示例

Essentially you can get all the properties of this by using the typeof(this).GetProperties() method. 从本质上讲,你可以得到的所有属性this通过使用typeof(this).GetProperties()方法。 That will return you a list of PropertyInfo objects that you can then iterate through as I did in the fiddle. 这将为您返回PropertyInfo对象的列表,然后您可以像在小提琴中一样进行迭代。 However, if there are any other properties on this you will also grab those, so you can use BindingFlags within the overload of the GetProperties function. 但是,如果有任何其他的属性this也将抓住这些,所以你可以使用的BindingFlags的过载范围内的GetProperties功能。

In the end it will probably be best for you to create some sort of container that has properties that you expect and want to iterate through. 最后,最好是创建一种具有您期望并希望迭代的属性的容器。 Or better yet, you may just have to accept that you are going to do a lot of FirstOrDefaults , which is a much safer route to go. 或者更好的是,您可能只需要接受要执行很多FirstOrDefaults ,这是一条更安全的方法。 Reflection can be tricky and confusing 反思可能会很棘手和令人困惑

Feel free to ask any questions and I'll be happy to go into more detail 随时问任何问题,我很乐意进一步详细介绍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM