Skip to content
Advertisement

choose a few id from db C#

I have a database and excel file

And I want to export strings to excel

How to export strings with 1 id I know

The code you can see below

_Hours = Rep.Where(o => o.Projects.ProjectGroupID == 4).Where(o => o.Projects.ProjectType == 1).Sum(o => (decimal?)o.TaskEfforts) ?? 0m,

But how I can choose several id’s?

This does not work

 _Hours = Rep.Where(o => o.Projects.ProjectGroupID == 4).Where(o => o.ProjectDescriptionID == 10).Where(o => o.ProjectDescriptionID == 17).Where(o => o.ProjectDescriptionID == 18).Where(o => o.ProjectDescriptionID == 19).Where(o => o.ProjectDescriptionID == 21).Where(o => o.ProjectDescriptionID == 24).Where(o => o.ProjectDescriptionID == 26).Where(o => o.Projects.ProjectType == 1).Sum(o => (decimal?)o.TaskEfforts) ?? 0m,

I know, that it is an error, but how can I choose some ID’s?

Thanks for answers.

Advertisement

Answer

The reason it didn’t work is because each where clause is working on a subset of data that the previous one put out.

Use a list for your LINQ query’s boolean logic.

List<int> ids = new List<int>{ 10, 17, 13, 7 };

_Hours = Rep.Where(o => ids.Contains(o.Projects.ProjectGroupID)).Where(o => o.Projects.ProjectType == 1).Sum(o => (decimal?)o.TaskEfforts) ?? default(int);

By manipulating the boolean this way, you can essentially convert a list of ints into a list of objects.

For your second where clause, I see you’re needing a different attribute to restrict the list even further. This would work, since each where clause operates on the results of the first, but for the reader’s sake it should be a &&.

_Hours = Rep.Where(o => ids.Contains(o.Projects.ProjectGroupID) && o.Projects.ProjectType == 1).ToList();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement