Return an item from the list using LINQ

advertisements

I have a list that contains 3 variables, expense, salary and year. I would like to return all expenses from the list using LINQ. Writing a foreach loop would suffice but I was hoping to archive something more efficient using LINQ.

I'm thinking something like this:

List<Company> ListCompanies = new List<Company>();

Company company1 = new Company() { Expense = 200, Salary = 1000, Year = new DateTime(2014, 1, 1).ToString("yyyy/mm/dd") };
Company company2 = new Company() { Expense = 300, Salary = 800, Year = new DateTime(2014, 2, 1).ToString("yyyy/mm/dd") };
Company company3 = new Company() { Expense = 500, Salary = 1400, Year = new DateTime(2014, 3, 1).ToString("yyyy/mm/dd") };

ListCompanies.Add(company1);
ListCompanies.Add(company2);
ListCompanies.Add(company3);

var Exp = ListCompanies.Where(e => ListCompanies.Contains(e.Expense));

This doesn't work as I'm getting this error:

Argument 1: cannot convert from 'int' to 'Project1.Company

I know I could get the direct values out of a LINQ query like this:

var CompanyName = ListCompanies.Where(cn => cn.Name.Contains("X"));

which would give me all company names that contains "X". Isn't it possible to get all company names in ListConpanies?

Hope I'm not to unclear.

Thanks!


You can get all salaries into a separate list with a Select:

var allSalaries = ListCompanies.Select(c => c.Salary).ToList();

This produces a list wit {1000, 800, 1400}

If you do not want a list, but wish to iterate over a particular attribute from your list, you can do a Select in a foreach loop:

foreach (var expense in ListCompanies.Select(c => c.Expense)) {
    ...
}