我有一个班级
public class RoomAvail
{
public int OCCUPANCY { get; set; }
public int ChildCount { get; set; }
public string ChildAges { get; set; }
}
我有RoomAvail列表,即列表房间;
rooms = { new RoomAvail{OCCUPANCY =1,ChildCount =1,ChildAges ="1" }
new RoomAvail{OCCUPANCY =2,ChildCount =2,ChildAges ="1,2" }
new RoomAvail{OCCUPANCY =3,ChildCount =3,ChildAges ="1,2,3" }
}
我填充了房间的价值。
我有List listAge = {12,13,14,14}
我的要求: 如果列表中的任何OCCUPANCY = 2,我应该在ChildAges中附加listAge的值。
最终输出:
rooms = { new RoomAvail{OCCUPANCY =1,ChildCount =1,ChildAges ="1" }
new RoomAvail{OCCUPANCY =2,ChildCount =2,ChildAges ="1,2,12,13,14,15" }
new RoomAvail{OCCUPANCY =3,ChildCount =3,ChildAges ="1,2,3" }
}
我只想更新房间变量。
我在做:
rooms.Where(y => y.OCCUPANCY == 2)
.Select(x => x.ChildAges)
.Aggregate((i, j) => i + listAge + j);
由于
答案 0 :(得分:2)
LINQ
不会修改您的对象。使用循环
foreach(var room in rooms.Where(y => y.OCCUPANCY == 2))
{
room.ChildAges = string.Join(",", room.ChildAges.Split(',').Concat(listAge));
}
答案 1 :(得分:1)
你可以尝试这个:
// Get the rooms with OCCUPANCY value equal to 2.
rooms = rooms.Where(x=>x.OCCUPANCY==2);
// Iterate through the selected rooms.
foreach(var room in rooms)
{
// Build a list of integers based on the room's list age.
List<int> currentListAge = room.ChildAges.Split(',').Select(int.Parse).ToList();
// Concat the currentListAge with the listAge, order the resulting list and
// then build a comma separated value list.
room.ChildAges = String.Join(",", currentListAge.Concat(listAge)
.OrderBy(x=>x)
.Select(x=>x.ToString())
.ToList());
}