LINQ to Entities multiple columns need 1 to be distinct - linq

I am trying to select multiple columns from an entity object but I want 1 property to be distinct. I am very new to both LINQ and Entity Framework so any help will be useful.
Here is my LINQ query so far:
var listTypes = (from s in context.LIST_OF_VALUES
orderby s.SORT_INDEX
select new { s.LIST_TYPE, s.DISPLAY_TEXT });
I want s.LIST_TYPE to be distinct. I figure using the groupby keyword is what I want (maybe?) but I have not found a way to use it that works.
Thank you.

Assuming DISPLAY_TEXT matches LIST_TYPE somehow (so you don't lose any information):
var distinct = context.LIST_OF_VALUES
.OrderBy(s => s.SORT_INDEX)
.GroupBy(s => s.LIST_TYPE)
.Select(g => new { g.Key, g.First().DISPLAY_TEXT });

Related

NotSupportedException for LINQ Queries

I am trying to get a list of a database table called oracleTimeCards whose employee id equals to the employeeID in employees list. Here is what I wrote:
LandornetSQLEntities db = new LandornetSQLEntities();
List<OracleEmployee> employees = db.OracleEmployees.Where(e => e.Office.Contains(officeName) && e.IsActive == true).Distinct().ToList();
var oracleTimeCards = db.OracleTimecards.Where(c => employees.Any(e => c.PersonID == e.PersonID)).ToList();
Anyone has any idea?
I'm going to assume you're using Entity Framework here. You can't embed calls to arbitrary LINQ extension methods inside your predicate, since EF might not know how to translate these to SQL.
Assuming you want to find all the timecards for the employees you found in your first query, you have two options. The simplest is to have a navigation property on your Employee class, named let's say TimeCards, that points to a collection of time card records for the given employee. Here's how that would work:
var oracleTimeCards = employees
.SelectMany(e => e.TimeCards)
.ToList();
If you don't want to do this for whatever reason, you can create an array of employee IDs by evaluating your first query, and use this to filter the second:
var empIDs = employees
.Select(e => e.PersonID)
.ToArray();
var oracleTimeCards = db.OracleTimecards
.Where(tc => empIDs.Contains(tc.PersonID))
.ToList();

linq query with count

I would like to create a simple linq query, but I don't really know, how it should be. I have searched the net, but found nothing, what I can use or I don't know yet, that I could use it.
So, basically, I have a table with this fields: reference, vat_code, amount, vat_amount, supplier.
Now, I would like to query the records, where reference<>'' and the reference is more than once in the table. But I need all the occupians.
F.e. from
1;VF;100;27;345
2;VF;200;54;123
2;VF;-200;-54;123
2;VF;200;54;123
3;VF;300;81;888
to
2;VF;200;54;123
2;VF;-200,-54;123
2;VF;200;54;123
How would be look the linq query to this?
Thanks.
If rows with same reference should go together in results, then you should filter out rows with reference equal to empty string, then group all rows by reference and select only those groups which have more than one row.
C# sample with DataTable:
var result = dt.AsEnumerable()
.Where(r => r.Field<string>("reference") != "")
.GroupBy(r => r.Field<string>("reference"))
.Where(g => g.Count() > 1)
.SelectMany(g => g); // flatten group to sequence of rows

preserving the order of returning entities when using .Contains(Id)

I want to hydrate a collection of entities by passing in a List of Ids and also preserve the order.
Another SO answer https://stackoverflow.com/a/15187081/1059911 suggested this approach to hydrating the entities which works great
var entities = db.MyEntities.Where(e => myListOfIds.Contains(e.ID)).ToList();
however the order of entities in the collection is different from the order of Ids
Is there a way to preserve the order?
May be that helps:
var entities = db.MyEntities
.Where(e => myListOfIds.Contains(e.ID))
.OrderBy(e => myListOfIds.IndexOf(e.ID)).ToList();
EDIT
JohnnyHK clarified that this will not work with LINQ to Entities. For this to work you need to order IEnumerable instead of IQueryable, since IQueryProvider don't know how to deal with local list IndexOf method when it sends query to server. But after AsEnumerable() OrderBy method deals with local data. So you can do this:
var entities = db.MyEntities
.Where(e => myListOfIds.Contains(e.ID))
.AsEnumerable()
.OrderBy(e => myListOfIds.IndexOf(e.ID)).ToList();
Entity Framework contains a subset of all of the LINQ commands so you won't have all the commands that LINQ to Objects has.
The following approach should give you your list of MyEntities in the same order as supplied by myListOfIds:
var entities = myListOfIds.Join(db.MyEntities, m => m, e => e.ID, (m,e) => e)
.ToList();

How to return distinct rows from and Entity with related Entities

I have an Entity that has an association to other Entities (related entities). I'm trying to return distinct rows from the primary entity which needs to include the data from the related entity so I can use one the related entity's properties downstream.
Below is the statement I'm using but it is not returning any rows. What's the best way to do this?
Below is my code.
return context.UserDisplays.Include("CurrentJob").Where(d => d.UserName == userName).GroupBy(d => d.CurrentJob.JobNo).Select(g => g.FirstOrDefault()).ToList();
Any help would be greatly appreciated!
Edit - For ComplexProperty
I believe once you do a GroupBy all Include methods are ignored. So you will need to iterate the list and call the LoadProperty method on each item. It should look something like this
var list = context.UserDisplays
.Where(d => d.UserName == userName)
.GroupBy(d => d.CurrentJob.JobNo)
.Select(g => g.FirstOrDefault()).ToList();
foreach(var item in list)
{
context.LoadProperty(item, "CurrentJob");
}
return list;
Resource Link
Check out the Distinct (Set Operators) section in this article
http://msdn.microsoft.com/en-us/vcsharp/aa336746
Are you asking for the Distinct UserDisplays? or the Distinct User or the Disticnt Jobs?
I would try say something like
var object = (from userDisplay in context.UserDisplays.Include("CurrentJob")
.Where userDisplay.UserName == userName
Select userDisplay).Distinct();
(sorry, im going off of my VB style but it should be about the same...)

How do dynamically set group by properties and aggregates in a LINQ query?

I assume I need to use the method call syntax instead of the query expression form, and I know the basics of grouping in the latter. Maybe some gurus can give caveats and advice on using group fields and aggregates obtained at runtime from a configuration, for use in a reporting like structure.
Have you looked at Dynamic Linq? It should do what you want. Have a look at this post from scottgu's blog.
If your data is in xml, linq to xml would allow you to write queries against it in which the certain inputs are strings.
For example:
System.Xml.Linq.XElement myData = GetData();
System.Xml.Linq.XElement result = new XElement("Result",
myData.Elements("Customer")
.GroupBy(e => e.Attributes("Name"))
.Select(g => new XElement("CustomerResult",
new XAttribute("Name" = g.Key,
new XAttribute("Count" = g.Count(),
new XAttribute("MinDate" = g.Min(e => e.Date)
)
);

Resources