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 on开发者_如何学Cly? 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 GetClientsByID
code 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:
IEnumerable<string> names = clientL.Select(x => x.Name);
or as a List<string>
:
List<string> names = clientL.Select(x => x.Name).ToList();
If you're certain there's going to be exactly one value you can use Single
:
string name = clientL.Select(x => x.Name).Single();
If there could be zero or one, you can use SingleOrDefault
:
// name will be null if clientL was empty
string name = clientL.Select(x => x.Name).SingleOrDefault();
(There's also First
, FirstOrDefault
etc.)
Well since all you're doing is creating a list of one item.. Assuming Name is a public property..
clientL[0].Name
should do it
You can use LINQ to retrieve this information:
List<string> clientNames = clientL.Select(c => c.Name).ToList();
You can use LINQ methods for this:
string clientName = clientL.Where(client => client.ID == 1).Select(client => client.Name).FirstOrDefault();
Or to retrieve all the names:
List<string> clientNameList = clientL.Select(client => client.Name).ToList();
try this:
List<string> clientL = ClientsInfo.GetClientsByID(client_id).Select(x => x.Name).ToList();
This will give you a list of names only.
Using LINQ:
var names = from c in ClientsInfo.GetClientsByID(client_id)
select c.Name;
names
is then an IEnumerable<string>
containing all names.
If thats not what you want please explain your question again.
精彩评论