从对象列表中的属性中删除空格?

时间:2017-03-15 14:13:11

标签: c# linq

我有这个对象列表:

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"}
}

如何使用linq删除区域中的空格和地址变量中的属性?

2 个答案:

答案 0 :(得分:0)

部分使用lynq完成:

items = items.Select(x => new Location() { area = x.area.Trim(), address = x.address.Trim(), sensorId = x.sensorId }).ToList();

答案 1 :(得分:0)

IMO Linq不应该用于此,但如果您愿意,可以试试这个:

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