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
125 views
in Technique[技术] by (71.8m points)

How to replace mutliple values in a list in c#?

If I have a list of 100 integers, how would I assign the values at index 20 to 50 to a different set of values in a list of length 31 without the use of loops? Coming from python this is very easy to do without looping but am unsure if it is possible to do in c#.


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

1 Answer

0 votes
by (71.8m points)

Using LINQ, which is "without using loops in my code", you could:

hundredInts.Take(19).Concat(thirtyoneInts).Concat(hundredInts.Skip(50));

(and if you want it back as a list or array etc, the relevant ToXXX call on the end of it)

Or perhaps:

hundredInts.Select((n, i) => (i < 20 || i > 50) ? n : thirtyOneInts[i-20])

Or built in stuff:

hundredInts.RemoveRange(20, 31).InsertRange(20, thirtyOneInts);

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

...