C# 更新列表关联字符串
我有一节课C# 更新列表关联字符串,c#,linq,lambda,C#,Linq,Lambda,我有一节课 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" }
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" }
}
我已经计算了房间的价值
我有列表年龄={12,13,14,14}
我的要求:
如果列表中的任何占用率=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);
谢谢
LINQ
不会修改您的对象。使用一个循环
foreach(var room in rooms.Where(y => y.OCCUPANCY == 2))
{
room.ChildAges = string.Join(",", room.ChildAges.Split(',').Concat(listAge));
}
你可以试试这个:
// 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());
}
//获取入住率值等于2的房间。
房间=房间。其中(x=>x.占用率==2);
//遍历选定的房间。
foreach(房间中的var房间)
{
//根据文件室的列表年龄构建整数列表。
List currentListAge=room.ChildAges.Split(',).Select(int.Parse.ToList();
//将currentListAge与listAge合并,对结果列表进行排序,然后
//然后构建一个逗号分隔的值列表。
room.ChildAges=String.Join(“,”,currentListAge.Concat(listAge)
.OrderBy(x=>x)
.Select(x=>x.ToString())
.ToList());
}