1

I have a list and data as follows.

public class Test
{
 public int Id {get;set;}
 public string Name {get;set;}
 public string Quality {get;set;}
}

Test test = new Test();
//db call to get test data
//test = [{1,'ABC','Good'},{2,'GEF','Bad'}]

I have to modify the list such that Name should be only the first 2 characters and Quality should be the first letter.

Expected Output:

//test = [{1,'A','G'},{2,'GE','B'}]

I tried to achieve with Linq foreach as follows. But I am not sure to write conditional statements inside forloop within Linq which resulted in error.

test.ForEach(x=> return x.Take(1))
1
  • You could override ToString function inside Test class, In that function you could substring all fields as u wish, and return a string. Commented Feb 8, 2022 at 10:55

2 Answers 2

3

List.ForEach is not LINQ though

test.ForEach(t => { t.Name = t.Name.Length > 2 ? t.Name.Remove(2) : t.Name; t.Quality = t.Quality.Length > 1 ? t.Quality.Remove(1) : t.Quality; });

Better would be to simply call a method that does this.

test.ForEach(Modify);

private static void Modify(Test t)
{
    // ,,,
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use simply use String.Substring as follows:

test.ForEach(s =>
{
    s.Name = s.Name.Substring(0, 2);
    s.Quality = s.Quality.Substring(0, 1);
});

Thanks, @Tim for pointing out that if Name or Quality is short then this code throws an exception. See Problem with Substring() - ArgumentOutOfRangeException for the possible solutions for that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.