简体   繁体   中英

Dynamic Linq FirstOrDefault Statement

Using C# 7+, I am instantiating a variable via a FirstOrDefault() statement. 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)

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

Essentially you can get all the properties of this by using the typeof(this).GetProperties() method. That will return you a list of PropertyInfo objects that you can then iterate through as I did in the fiddle. 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.

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. Reflection can be tricky and confusing

Feel free to ask any questions and I'll be happy to go into more detail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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