Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c# - Use a foreach loop within a foreach loop in a linq query

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?

question from:https://stackoverflow.com/questions/65852140/use-a-foreach-loop-within-a-foreach-loop-in-a-linq-query

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...