I am wondering on how to do the following. I have the Linq query:
Items items.Where(i => i.GetType() == typeof(SubItem))
.Cast<SubItem>()
.ToList()
.ForEach(i => i.SomeList.Add(i.SomeObject.ForEach(i => i.SomeString)));
My question is about i.SomeList.Add()
. I want to return a couple of string values to i.SomeList.Add()
from i.SomeObject
but I do not know how I can do this in this way? Is it even possible like this to have another ForEach Loop within a Linq ForEach usinq Linq query?
I believe this foreach
loop will achieve your goal, if I've understood the problem.
It will loop over any element of items
that is a (or is derived from) SubItem
. It will then select all SomeObject.SomeString
strings and add them to the SomeList
.
foreach (var subItem in items.OfType<SubItem>()) {
subItem.SomeList.AddRange(subItem.SomeObject.Select(o => o.SomeString));
}
This is a compilation of suggestions from Panagiotis Kanavos, juharr, and Aluan Haddad.
LINQ isn't really for running Add
operations... it's much more powerful when you think of it as returning a resultset.
So instead of
//Add every value of SomeField to targetList
sourceList.ForEach( x => targetList.Add(x.SomeField) )
Think of doing it this way:
//Create a list of all instances of SomeField and assign it to targetList
targetList = sourceList.Select( x => x.SomeField).ToList();
Or if you need to keep the existing items in the target list, do this:
//Create a list of all SomeFields and add it to targetList
targetList.AddRange
(
sourceList.Select( x => x.SomeField )
);
Similarly, instead of using a nested foreach, consider using SelectMany
.
I'm not completely clear on your requirements but you probably want something like this:
//To SomeList, add the SomeString field from all instances of SomeObject
someList.AddRange
(
items.OfType<SubItem>().SelectMany( x => x.SomeObject ).Select( x => x.SomeString )
);
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.