How can I set properties on all items from a linq query with values from another object that is also pulled from a query?

北战南征 提交于 2019-12-01 14:07:21

问题


I have a query pulling from a database:

List<myClass> items = new List<myClass>(from i in context
                      select new myClass
                      {
                          A = i.A,
                          B = "",    // i doesn't know this, this comes from elsewhere
                          C = i.C
                      }

I also have another query doing a similar thing:

List<myClass2> otherItems = new List<myClass2>(from j in context
                            select new myClass2
                            {
                                A = j.A,   // A is the intersection, there will only be 1 A here but many A's in items
                                B = j.B
                            }

In reality these classes are much larger and query data that is separated not only by database but by server as well. Is it possible to use a LINQ query to populate the property B for all items where items.A intersect? All of the built in LINQ predicates appear only to do aggregates, selections or bool expressions.

In my brain I had something like this, but this is all off:

items.Where(x => x.B = (otherItems.Where(z => z.A == x.A).Single().B));

Or am I being ridiculous with trying to make this work in LINQ and should just abandon it in favor of a for loop where the actual setting becomes trivial? Because of deadlines I will be resorting to the for loop (and it's probably going to end up being a lot more readable in the long run anyway), but is it possible to do this? Would an extension method be necessary to add a special predicate to allow this?


回答1:


LINQ is designed for querying. If you're trying to set things, you should definitely use a loop (probably foreach). That doesn't mean you won't be able to use LINQ as part of that loop, but you shouldn't be trying to apply a side-effect within LINQ itself.




回答2:


Query the OtherItems first. Do a ToDictionary() on the result. Then, when querying the database, do this:

var items = from i in context
   select new myClass 
   { A = i.A, 
     B = otherItems[i.A], 
     C = i.C
   } 


来源:https://stackoverflow.com/questions/7851890/how-can-i-set-properties-on-all-items-from-a-linq-query-with-values-from-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!