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?
ForEachis a List method, not LINQ. LINQ is a query language. Why use it at all if you want nested loops?ForEachis absolutely wrong here as areCast,i.GetType() == typeof(SubItem), andToList.Where(i => i.GetType() == typeof(SubItem)).Cast<SubItem>()is equivalent toOfType<SubIttem>(). What are you trying to do anyway?ForEachdoesn't return anything, soi.SomeArray.Add(i.SomeObject.ForEachwon't even compile. Whatever you want to do, it's far easier to do with simple loopsi.SomeArray.AddRange(i.SomeObject.Select(x => x.SomeString))though that only works ifSomeArrayis aList<T>and not an array as the name implies.GetType()is slow and will miss any types that derive fromSubItem.ToListisn't necessarily wrong but it's confusing here and people often use it without thinking. Instead useforeach (var item in items.OfType<SubItem>()) {...}