-3

I have the following query:

Locations.ForEach(a => a.Name = a.Name.Replace(@"/", @" ").Replace(@"\", @" ");

What I like to do is if the Name has a length of greater than 31 characters, I like to trim upto the 31st character. Is there each easy way to do this with the .ForEach I have.

mjwills
  • 23,389
  • 6
  • 40
  • 63
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

2 Answers2

1

One way to accomplish this is to use a combination of the System.Linq extension method Take to "take" the number of characters you want from the beginning of the string and string.Concat to combine those characters back to a string, and then use this for the new value.

Using your example:

int maxLength = 31;
Locations.ForEach(a => 
    a.Name = string.Concat(a.Name.Replace(@"/", @" ").Replace(@"\", @" ").Take(maxLength));

Or a full compile-able example:

public class Location
{
    public string Name { get; set; }
    public override string ToString()
    {
        return Name;
    }
}

private static void Main()
{
    var locations = new List<Location>();
    var maxLength = 5;

    // Populate our list with locations that have an ever growing Name length
    for (int i = 0; i < 10; i++)
    {
        locations.Add(new Location {Name = new string('*', i)});
    }

    Console.WriteLine("Beginning values:");
    locations.ForEach(Console.WriteLine);

    // Trim the values
    locations.ForEach(l => l.Name = string.Concat(l.Name.Take(maxLength)));

    Console.WriteLine("\nEnding values:");
    locations.ForEach(Console.WriteLine);

    GetKeyFromUser("\nDone! Press any key to exit...");
}

Output

enter image description here

Rufus L
  • 36,127
  • 5
  • 30
  • 43
1

Or example with Substring:

  const int maxLength = 31;  
  Locations.ForEach(a => a.Name = a.Name
    .Substring(0, Math.Min(a.Name.Length, maxLength))
    .Replace(@"/", @" ")
    .Replace(@"\", @" "));
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116