Getting objects using LINQ and stored procedure - c#

I have a stored procedure that is returning data in this format:
EmployeeID | DepartmentID
---------------------
1 | 1
2 | 1
3 | 2
4 | 4
5 | 4
I'm getting the results like so:
List<spResult> results = DataContext.sp().ToList();
I'd like to get a list of Employees for a certain Department, based on the data returned from the stored procedure. Something like:
int departmentId = 1;
List<Employee> employees = (from e in DataContext.Employees
//where...
select e).ToList();
How do I format my where clause to get the EmployeeIDs from the result set that have the given DepartmentID?

How about:
List<spResult> results = DataContext.sp().ToList();
int departmentId = 1;
var departmentEmployees = from de in results
where de.DepartmentId == departmentId
select de.EmployeeID;
List<Employee> employees = (from e in DataContext.Employees
where departmentEmployees.Contains(e.ID)
select e).ToList();

You could get a subset of keys:
var empKeys = results.Where(i => i.DepartmentID = departmentID);
And then use this list in the query like:
List<Employee> employees = (from e in DataContext.Employees
where empKeys.Contains(e.EmployeeID)
select h).ToList();
HTH.

You should also be able to do something like this:
List<Employee> employees = DataContext.Employees.Where(e => empKeys.Contains(e.EmployeeID)).ToList()

Related

LINQ Lambda group by multiple columns following by select multiple columns

Lets assume we have some data in a table:
Id OrderNr Name Date
1 1 John 2011-01-01
2 1 John 2012-01-01
3 2 Paul 2011-02-02
I want to use linq (lambda expressions) to group by OrderNr and Name and select OrderNr, Name and First occuring Date. So the result should be:
OrderNr Name Date
1 John 2011-01-01
2 Paul 2011-02-02
How should this be written?
This should work:
var results1 = (from t in DB.Table
group t by new { t.OrderN, t.Name } into grp
select new
{
OrderN = grp.Key.OrderN,
Name = grp.Key.Name,
FirstDate = grp.FirstOrDefault().Date
}).ToList();

Not a simple Max

I have the following data:
Id | Value | OtherStuff
---------------------------
6 | 6 | 1
---------------------------
5 | 4 | 2
---------------------------
5 | 2 | 3
The desired result:
Id | Value | OtherStuff
---------------------------
6 | 6 | 1
---------------------------
5 | 4 | 2
That is I need the Max Value for each of the Id's.
I'm a bit stumped of how to do this without breaking it into multiple queries, can it be done, and if so how?
Update: I think I oversimplified the issue:
var query = from st in StockStakes
join o in Organisations on j.OrganisationId equals o.OrganisationId into oGroup
from o in oGroup.DefaultIfEmpty()
where st.Stock.Status == "A"
select new
{
Id = st.Id,
Value = st.Value,
CustomerId = o.OrganisationId
};
The data sample from above still stands... now how do i structure the query to give me the Max Value alongside each Id?
var query = from x in data
group x by x.Id into x
select x.OrderByDescending(y => y.Value).FirstOrDefault()
Based on you updated query, similar approach to the first query, but since you have multiple tables you need to group all the tables into an anonymous object and then select only the columns you want
var query = from st in StockStakes
join o in Organisations on j.OrganisationId equals o.OrganisationId into oGroup
from o in oGroup.DefaultIfEmpty()
where st.Stock.Status == "A"
group new { st, o } by st.Id into g
let largestValue = g.OrderByDescending(x => x.Value).FirstOrDefault()
select new
{
Id = g.Key,
Value = largestValue.st.Value,
CustomerId = largestValue.o.OrganisationId
};
I'm not really sure about what you mean, but maybe you can try with this query.
select Id, max(Value)
from your_table
group by Id;
This gives you the max "Value column" value for each "Id column" value.
-- EDIT --
LINQ version:
var q = from t in dc.YourTable
group t by t.Id
into g
select new
{
Id = g.Id,
Value = (from t2 in g select t2.Value).Max()
};
Code not tested. I'm on the bus now... :-) Give it a try!

Join 3 tables and databind to a ComboBox

Good morning SO.
I have 3 tables (Sql Server) with this layout:
GenreMovies: | RowID | MovieGenre|
GenreMusic: |RowID | MusicGenre |
GenrePodcast:| RowID | PodcastGenre|
I have a combobox/dropdown that I am trying to populate with a Query:
var infoQuery =
(from MovieGen in dbContext.GenreMovies
select MovieGen.RowID)
.Union
(from MusicGen in dbContext.GenreMusics
select MusicGen.RowID).Union(from PodcastGen in dbContext.GenrePodcasts select PodcastGen.RowID).ToList();
GridSortSearch.DataTextField = "MovieGenre";
GridSortSearch.DataSource = infoQuery;
GridSortSearch.DataBind();
I have two issues the query is only being populated with "RowID"
and the combobox/dropdown is failing at the "DataTextField"
Like I said you need to return the same rows on results to achieve what you want.
Something like this, notice the change to the selects and the name of DataTextField value.
var infoQuery =
(from MovieGen in dbContext.GenreMovies
select new { MovieGen.RowID, Genre=MovieGen.MovieGenre})
.Union
(from MusicGen in dbContext.GenreMusics
select new {MusicGen.RowID, Genre=MusicGen.MusicGenre).Union(from PodcastGen in dbContext.GenrePodcasts select new {PodcastGen.RowID, Genre=PodcastGen.PodcastGenre).ToList();
GridSortSearch.DataTextField = "Genre";
GridSortSearch.DataSource = infoQuery;
GridSortSearch.DataBind();
I couldn't compile/test this where I am at the moment but should work.

Linq query to select data from table and join 2 tables

I am trying to select everything from a table and then make a join with two other tables, from which I need just some of the columns. The final list will be populated into a DevExpress GridControl. The main table that I take the data from has these columns:
Id | ScheduleId | AccountId | Description
I can easily select everything from this table and return. Here is my list:
public IList<StatusDescription> getStatusDescription()
{
var listOfItems = from e in context.StatusDescription select e;
return listOfItems.ToList<StatusDescription>();
}
The other two tables are Schedules and Accounts, they look as follows:
Id | ScheduleName | DateFrom | DateTo
and
Id | AccountName | AccountCode
I would like to join the DateFrom and DateTo from the Schedule table and the AccountCode from the Account table. Is it possible to get all that into a single list. I can easily bind it later to the GridControl
var listOfItems = from e in context.StatusDescription
join s in context.Schedules on e.ScheduleId equals s.Id
join a in context.Accounts on e.AccountId equals a.Id
select new
{
Description = e.Description,
ScheduleStart = s.DateFrom,
ScheduleEnd = s.DateTo,
AccountCode = a.AccountCode
}
var Query = from p in context.StatusDescription
select new
{
p.Id,
p.Description,
p.Schedule.DateFrom,
p.Schedule.DateTo,
p.Account.AccountCode
};
hope it helps

C# Linq finding value

I want to return the depart number that is not found Employee Table by comparing Department table.
Person Table
ID name salary job commision DeptID
--------------------------------------------------------------
P001 Jon 2000 Manager NULL 1
P002 Skeet 1000 Salesman 2000 1
P003 James 2340 Developer NULL 2
P004 greed 4500 Developer NULL 2
P005 Joel 1330 Salesman 1200 1
P006 Deol 5000 Architect NULL 2
Department Table
DeptID DeptName
1 Management
2 Software
3 ERP
SQL
select DeptId from dept
where deptId not in (select deptid from person)
When i try to execute the below code
LINQ
var qry = from n in context.Persons
where n.DeptID !=
(from m in context.Depts select m.DeptId)
select new { DeptID = n.DeptID };
I receive the following error
Operator '!=' cannot be applied to operands of type 'int?' and 'System.Linq.IQueryable'
var qry = from n in context.Persons
where n.DeptID !=
(from m in context.Depts select m.DeptId).FirstOrDefault()
select new { DeptID = n.DeptID };
You are trying to compare DeptID with a collection 1 or more department Ids. Even if there would only logically be one result for a DeptID, syntactically you need to specify that you want the first hit.
Suggested rephrasing:
var q = from m in context.Depts
where
!context.Persons.Select(p => p.DeptID).Contains(m.DeptID)
select new { DeptID = m.DeptID };
It sounds that your DeptID field in SQL is set to allow nulls. In that case you'd probably want something along the lines of this:
var qry = from n in context.Persons
where n.DeptID.Value !=
(from m in context.Depts select m.DeptId)
select new { DeptID = n.DeptID.Value };
I think it should be something like that. I tried to get a list of DeptID's first and then implement a NOT IN with contains :
var deptIDs = context.Persons
.Where( p => !context.Depts
.Select(d => new {DeptID = d.DeptID})
.Contains( p.DeptID )
)
.Select( p => new { DeptID = n.DeptID } );

Categories

Resources