Home > Software engineering >  How can i get first n items of arrayList and set the value of those n items to something that i want
How can i get first n items of arrayList and set the value of those n items to something that i want

Time:12-18

Using Linq,how can I get first n items of array and set the value of those n items to something that I want?

Suppose i have an array List of 5 elements but i want to select first 2 items of array and change the value of those first 2 items and keep the rest array as it is.

Example

Array names = [Jason, Taylor, Robert, Amy]

I want to select first 2 items of array names and set another value inplace of those values. I want to change jason to Mike and Taylor to Mike

CodePudding user response:

If you have

string[] names = new [] {"Jason", "Taylor", "Robert", "Amy" };

and you want remove some names ("Jason", "Taylor") and insert some other names ("Mike")

string[] names = new [] {"Mike", "Robert", "Amy" };

you can try Linq:

using System.Linq;

... 

names = new string[] {"Mike"}.Concat(names.Skip(2)).ToArray();

If you want to replace ("Jason" -> "Mike", "Taylor" -> "Mike")

string[] names = new [] {"Mike", "Mike", "Robert", "Amy" };

just replace unwanted items with required:

names[0] = "Mike";
names[1] = "Mike";

in general case

int count = 2;

for (int i = 0; i < count;   i)
  names[i] = "Mike";

CodePudding user response:

I want to select the first 2 items of array names and set another value in place of those values. I want to change Jason to Mike and Taylor to Mike

You should be able to do this in one line:

 var result = names.Take(2).Select(x => x = "Mike").Concat(names.Skip(2));

CodePudding user response:

List<string> list = new List<string>
for(int i=0; i<<n>; i  )
{
  list[i] = //new value
}
  •  Tags:  
  • linq
  • Related