Traverse a list and retrieve a specified value from List<> in asp.net/c#
I have a list which is defined as
List<SoftwareTitles> softwareTitlesList = new List<SoftwareTitles>();
and the SoftwareTitles is a class which is defines as follows:
public class SoftwareTitles
{
string softwareTitle;
string invoiceNumber;
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
this.softwareTitle = softwareTitle;
this.invoiceNumber = invoiceNumber;
}
string InvoiceNumber
{
get
{
return this.invoiceNumber;
}
}
string SoftwareTitle
{
get
{
return this.softwareTitle;
}
}
}
And now I'm adding the values from the sql server database to the list defines as follows:
public List<SoftwareTitles> SoftwareListRetrieve()
{
ConnectionToSql con1 = new ConnectionToSql();
string connectionString = con1.ConnectionStringMethod();
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd2 = new SqlCommand("SelectionOfSoftwareTitles", sqlConnection);
cmd2.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.HasRows)
{
while (dr2.Read())
{
String softwareTitle = (String)dr2[0];
String invoiceNumber = (String)dr2[1];
SoftwareTitles s1 = new SoftwareTitles(softwareTitle, invoiceNumber);
softwareTitlesList.Add(s1);
}
}
sqlConnection.Close();
dr2.Close();
return softwareTitlesList;
}
I want to find out the software title for every occurence of invoice number by looping through List<>. And I don't kno开发者_运维技巧w how ? I have tried to loop through the List<> by the following code. I wanted to use something like contains i.e., softwareTitlesList[i].contains but seems like there is no such property or method
for(int i=0; i<softwareTitlesList.Count;i++)
{
softwareTitlesList[i]. [BUT IT IS NOT SUGGESTING ME ANYTHING]
}
I'm stuck with this from morning. I don't how to solve this dilemma.
Please help me
Thanks in anticipation
search for an invoice number
string invoiceNumber = "111111111";
using linq
IList<string> titles = softwareTitlesList
.Where(st => st.InvoiceNumber == invoiceNumber)
.Select(st => st.SoftwareTitle);
or
IList<string> titles = softwareTitlesList
.Where(st => st.InvoiceNumber.Contains(invoiceNumber))
.Select(st => st.SoftwareTitle);
w/o using linq, it's still pretty basic
IList<string> titles = new List<string>();
foreach(var softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(invoiceNumber))
titles.Add(softwareTitle.SoftwareTitle);
}
you could also rewrite your class like this:
public class SoftwareTitles
{
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
SoftwareTitle = softwareTitle;
InvoiceNumber = invoiceNumber;
}
public string InvoiceNumber { get; private set; }
public string SoftwareTitle { get; private set; }
}
精彩评论