I have a class and in that class there is a function that returns a list of type Clients, the list contains all the information about the client, but now where I want to know how can I access the Name only for example of the list.. please see below
Function in ClientsInfo class:
public List<Clients> GetClientsByID(int clientID)
{
ClientsData cData = new ClientsData();
List<Clients> listClients = new List<Clients>();
DataTable dtClients = cData.GetClientsByID(clientID).Tables[0];
foreach (DataRow row in dtClients.Rows)
{
this.Name = row["Name"].ToString();
this.Address = row["Address"].ToString();
this.BussinessName = row["Bussiness"].ToString();
}
listClients.Add(this);
return listClients;
}
Name, Address and Bussiness are a property in this class.. now I am calling this list from somewhere else like this
List<Clients> clientL = ClientsInfo.GetClientsByID(client_id);
Now i got the information stored in clientL, how do I retrieve the Name only? of the client?
I’m assuming you’re using .NET 3.5 or higher, so you can use LINQ. I’d urge you to use LINQ in the
GetClientsByIDcode as well, in fact, but leaving that aside…Well you’ve got multiple clients here, not just one. So you can get the multiple names with:
or as a
List<string>:If you’re certain there’s going to be exactly one value you can use
Single:If there could be zero or one, you can use
SingleOrDefault:(There’s also
First,FirstOrDefaultetc.)