我应该使用哪个关键字"输入"

时间:2018-05-25 12:24:14

标签: c# uwp

在我的uwp项目中,我有一个名为Rooms的List,这是该列表中的内容:

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的值
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"
    });
}

2 个答案:

答案 0 :(得分:2)

如果您只是想编辑列表中第二个房间的属性,这就是它的样子,因为您使用的是index = 1(记住数组和列表从零开始),那么它非常简单。编辑:你说你想编辑第一个,所以唯一需要改变的是使用0作为索引。

Rooms[0].Projector = Visibility.Collapsed;

如果您正在尝试这样做,上述情况应该有效。

答案 1 :(得分:2)

这是你想要做的吗?

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);
}

或者使用单个转换代码行更简单(注意&#34; null&#34;下面可能需要调整为默认值,如果它是枚举)。这完全避免了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
    });