-1

I have this list of object:

public class Location
{
    public string area { get; set; }
    public string sensorId { get; set; }
    public string address { get; set; }
}

List<Location> items = List<Location>(){
new Location(){area = "london ", address ="king road", sensorId ="2134"},
new Location(){area = "moscow",  address ="george str", sensorId ="2134"},
new Location(){area = "york ",   address ="johnson str ", sensorId ="2134"},
new Location(){area = " tokyo",  address ="king road 5", sensorId ="2134"},
new Location(){area = "paris",   address ="elitom road", sensorId ="2134"}
}

how can I remove white spaces in area and address properties in items variable using linq?

Michael
  • 13,950
  • 57
  • 145
  • 288

2 Answers2

1

IMO Linq should not be used for this but if you want, you can try this one :

items = items.Select(item => {
    item.area = Regex.Replace(item.area, @"\s+", ""); // remove all white spaces
    item.address = Regex.Replace(item.address, @"\s+", ""); // remove all white spaces
    return item; // return processed item...
}).ToList(); // return as a List
mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
  • 1
    Why should you not use Linq for this? – Jim Mischel Mar 15 '17 at 14:18
  • 2
    @JimMischel You're not transforming the sequence into a new sequence, you're mutating the values in the sequence. LINQ isn't designed to do that. It's specifically designed to *not* do that. – Servy Mar 15 '17 at 14:19
  • 2
    @JimMischel Because a `for`/`foreach` loop would probably end up being more readable. Obviously it is opinionated though. – TheLethalCoder Mar 15 '17 at 14:19
  • 1
    @JimMischel No, it's not. It's creating a new sequence with exactly the same items in it, but mutating those items in the process of creating that new sequence. – Servy Mar 15 '17 at 14:21
  • Yeah, my mistake. I mis-read the code. I thought his code was similar to the other answer, which is not mutating the items. – Jim Mischel Mar 15 '17 at 14:22
0

Partly done using lynq:

items = items.Select(x => new Location() { area = x.area.Trim(), address = x.address.Trim(), sensorId = x.sensorId }).ToList();
cramopy
  • 3,459
  • 6
  • 28
  • 42
  • 1
    This only removes beginning and ending spaces, the OP wants to remove all whitespace – TheLethalCoder Mar 15 '17 at 14:17
  • Also they don't want to remove whitespace from `sensorId` – TheLethalCoder Mar 15 '17 at 14:18
  • @TheLethalCoder you're right for `sensorId`, but it was not clearly specified to remove all whitespaces -- according to the question I interpreted it as trim the required ones – cramopy Mar 15 '17 at 14:20
  • 1
    @cramopy It said to remove whitespace. Not whitespace at the start and end. *That* is what you'd need to specifically specify if that were the desired behavior. – Servy Mar 15 '17 at 14:20