I have a class:
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; }
}
Now I have a List<Server>
and want to get the property "status" for a given ServerID.
How?
Using Linq:
string GetServerStatus(string id)
{
var server = servers.FirstOrDefault(s => s.ServerId == id);
if (server != null)
return server.Status;
return null;
}
Server serverById=servers.FirstOrDefault(x=>x.ServerId=="1");
if(serverById!=null)
{
MessageBox.Show(serverById.Status);
}
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;
}
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;
}
You can use a from clause (see 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.