我有一个包含3个变量,费用,工资和年份的列表。 我想使用LINQ从列表中返回所有费用。 编写一个foreach循环就足够了,但我希望使用LINQ来存档更有效的东西。
我在想这样的事情:
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));这不起作用,因为我收到此错误:
参数1:无法从'int'转换为'Project1.Company
我知道我可以从这样的LINQ查询中获取直接值:
var CompanyName = ListCompanies.Where(cn => cn.Name.Contains("X"));这会给我所有包含“X”的公司名称。 是不是可以在ListConpanies获得所有公司名称?
希望我不清楚。
谢谢!
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!
最满意答案
您可以使用Select将所有工资列入单独的列表:
var allSalaries = ListCompanies.Select(c => c.Salary).ToList();这会产生一个列表{1000, 800, 1400}
如果您不想要列表,但希望迭代列表中的特定属性,则可以在foreach循环中执行Select :
foreach (var expense in ListCompanies.Select(c => c.Expense)) { ... }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)) { ... }更多推荐
发布评论