在我的 uwp 项目中,我有一个被调用的列表,Rooms
这是该列表中的内容:
public string RoomID { get; set; }
public string RoomName { get; set; }
public Visibility Projector { get; set; }
public int Seats { get; set; }
public string FrontImage { get; set; }
public string Note { get; set; }
我正在尝试插入一个值Projector
in
Rooms.Add(new Room
{
RoomID = id,
RoomName = name,
FrontImage = Img1,
Seats = seats,
Note = "Lorem ipsum dolor sit amet, co"
});
有了这行代码。
Rooms.Insert(1, new Room{ Projector = Visibility.Collapsed });
但是,当我使用关键字new
创建一个新房间时,是否还有其他关键字可以用于将“投影仪”值插入到我现有的房间中?
提前致谢!
编辑:
foreach (var room in data)
{
string id = room.id;
string name = room.name;
int seats = room.seats;
List<Roomattribute> roomattrib = room.roomAttributes;
foreach (var attri in roomattrib)
{
int attriId = attri.id;
string attriName = attri.name;
int attriIcon = attri.icon;
if (attriId == 1)
{
Rooms.Insert(0, new Room{ Projector = Visibility.Collapsed });
}
}
Rooms.Add(new Room
{
RoomID = id,
RoomName = name,
FrontImage = Img1,
Seats = seats,
Note = "Lorem ipsum dolor sit amet, co"
});
}
这是你想要做的吗?
foreach (var room in data)
{
var newRoom = new Room()
{
RoomID = room.id,
RoomName = room.name,
FrontImage = Img1,
Seats = room.seats,
Note = "Lorem ipsum dolor sit amet, co"
};
//if any of the room's attribute's ID is 1
if (room.roomAttributes.Any(a => a.id == 1))
newRoom.Projector = Visibility.Collapsed;
Rooms.Add(newRoom);
}
或者甚至更简单,使用单个转换代码行(请注意,如果是枚举,则可能需要将下面的“null”调整为默认值)。这完全避免了 foreach,并且读起来非常简洁。这就是我编写这段代码的方式。
Rooms.AddRange(data.Select(a => new Room() {
RoomID = a.id,
RoomName = a.name,
FrontImage = Img1,
Seats = a.seats,
Note = "Lorem ipsum dolor sit amet, co"
Projector = a.roomAttributes.Any(a => a.id == 1) ? Visibility.Collapsed : null
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句