如何通过物业从列表中获取房产?

时间:2014-05-27 18:42:07

标签: c# list

我有一个班级:

public class Server
{
    public string ServerId { get; set; }
    public string Name { get; set; }
    public string Status { get; set; }
    public string Type { get; set; }
    public string Region { get; set; }
}

现在我有一个List<Server>,并希望获取给定ServerID的属性“status”。

如何?

5 个答案:

答案 0 :(得分:5)

使用Linq:

string GetServerStatus(string id)
{
    var server = servers.FirstOrDefault(s => s.ServerId == id);
    if (server != null)
        return server.Status;
    return null;
}

答案 1 :(得分:2)

Server serverById=servers.FirstOrDefault(x=>x.ServerId=="1");
if(serverById!=null)
  {
       MessageBox.Show(serverById.Status);
  }

答案 2 :(得分:0)

public string GetStatus(string serverID, List<Server> collection)
{
    string result = string.Empty;

    foreach(Server server in collection)
    {
         if (server.ServerID == serverID)
         {
             result = server.Status;
             break;
         }
    }

    return result;
}

答案 3 :(得分:0)

public Server FindServerByID(List<Server> list, string id)
{
     for (int i = 0; i < list.Count; i++)
         if (item[i].ServerID == id)
              return item;
     return null;
}

public string GetStatusForServerByID(List<Server> list, string id)
{
     var server = GetServerByID(list, id);
     return server == null
          ? null
          : server.Status;
 }

答案 4 :(得分:0)

您可以使用from子句(请参阅http://msdn.microsoft.com/en-us/library/bb383978.aspx):

List<Server> yourlist = new List<Server>()
var data = from x in yourlist where x.ServerId == "1" select x.Status;