How to Group and Order in a LINQ Query - c#

I would like to group & order by in a query builder expression. The following query gets me close to what i want but the order by does not appear to be working.
what i have is an object that has unique ids but some will have a common versionId. I would like to get the last edited item of the same versionId. So only one item per version id and i want it to be the last edited one.
IQueryable<Item> result = DataContext.Items.Where(x => (x.ItemName.Contains(searchKeyword) ||
x.ItemDescription.Contains(searchKeyword))
.GroupBy(y => y.VersionId)
.Select(z => z.OrderByDescending(item => item.LastModifiedDateTime).FirstOrDefault());
Edit: I don't really care about the order of the result set, i really just care about what item within the grouping is returned. I want to make sure that the last edited Item within a versionId group is return.

Your z parameter contains the individual group objects.
By calling OrderBy inside of Select, you're ordering the items in each group, but not the groups themselves.
You need to also call OrderBy after Select, like this:
.Select(z.OrderByDescending(item => item.LastModifiedDateTime).FirstOrDefault())
.Where(item => item != null)
.OrderByDescending(item => item.LastModifiedTime)

Related

Getting null data when executing LINQ to Entities query

I have the following Book table:
From this table, I am trying to get the latest registrationNumber based on the group ID as an input from the user.
So, my query looks like this at the moment:
var booksQuery = _context.Books.Where(g => g.GroupId == id)
.OrderByDescending(g => g.RegistrationNumber).GroupBy(g => g.GroupId);
id is the group Id specified by the user. So for example, if id = 15, then I should get the 15:6 as my latest registration number. To do that, I basically grouped by id and ordered the result by descending order. But that is giving me null results. Anyone know why? I am very new to this LINQ-Entitiy coding.
As mentioned by others you really should make your registrationNumber field an integer since you are wanting to sort on it. In the event, you can't make the change, below is a Linq query that basically parses the registration number and converts to an integer to sort on the first and second part by splitting at the colon. This works for sorting when you have 15:10, etc, as in the string sort 15:6 comes before 15:10
var booksQuery = books.Where(g => g.GroupId == id).ToList();
var bookWanted = booksQuery
.OrderByDescending(g => int.Parse(g.registrationNumber.Split(':')[0]))
.ThenByDescending(g=> int.Parse(g.registrationNumber.Split(':')[1]))
.FirstOrDefault();

EF Linq group by ICollection of objects

All,
I have a Linq query which fetches a list of events which works great. The problem I'm facing is that Events contains a ICollection of Artists called headliners and in the list I only want 1 event per,set of, Artist(s).
The query underneath works fine but: I require a top 10 of Events but only one Event per, set of, artist(s) for sorting the popularity of the artist with highest popularity can be used - not what i want.
Context.Events
.Where(x => x.Stage.Venue.AreaId == 1 && x.StartDateTimeUtc > DateTime.UtcNow && x.IsVerified)
.OrderByDescending(x => x.Headliners.Max(y => y.Popularity))
.Take(10)
.ToList();
How can I adjust the query above that I only get one Event per Artist. I would need to do some sort of grouping to see if the event is performed by same (set of) Artist(s).
I'm looking into using the Artist's primary key but because it is an collection i cannot get it to work. I already tried the String.Join to get a single unique key for the headliners. This is however not support in entity framework.
Is this something that can (gracefully) be supported by Linq to EF?
The following SQL query does almost what i want expect that it won't work with multiple artist for the same event
SELECT MAX(E.EventId), MAX(E.Name)
FROM [dbo].[Events] E
INNER JOIN [dbo].[Stages] S ON E.StageId = S.StageId
INNER JOIN [dbo].[Venues] V ON S.VenueId = V.VenueId
INNER JOIN [dbo].[Areas] A ON V.AreaId = A.AreaId
INNER JOIN [dbo].[Headliners] H ON E.EventId = H.EventId
INNER JOIN [dbo].[Artists] A2 ON A2.ArtistId = H.ArtistId
WHERE E.IsVerified = 1 AND E.StartDateTimeUtc>GETDATE() AND A.AreaId = 1
GROUP BY A2.ArtistId, A2.Name, A2.EchoNestHotttnesss
ORDER BY A2.EchoNestHotttnesss desc
Challenging task, but here it is:
var availableEvents = db.MusicEvents.Where(e =>
e.Stage.Venue.AreaId == 1 && e.StartDateTimeUtc > DateTime.UtcNow && e.IsVerified);
var topEvents =
(from e1 in availableEvents
where e1.Headliners.Any() &&
!availableEvents.Any(e2 => e2.StartDateTimeUtc < e1.StartDateTimeUtc &&
!e2.Headliners.Any(a2 => !e1.Headliners.Any(a1 => a1.Id == a2.Id)) &&
!e1.Headliners.Any(a1 => !e2.Headliners.Any(a2 => a2.Id == a1.Id)))
orderby e1.Headliners.Max(a => a.Popularity) descending
select e1)
.Take(10)
.ToList();
The first subquery (availableEvents) is just for reusing the "availability" filter inside the main query. It does not execute separately.
The critical part is the condition
!availableEvents.Any(e2 => e2.StartDateTimeUtc < e1.StartDateTimeUtc &&
!e2.Headliners.Any(a2 => !e1.Headliners.Any(a1 => a1.Id == a2.Id)) &&
!e1.Headliners.Any(a1 => !e2.Headliners.Any(a2 => a2.Id == a1.Id)))
The idea is to exclude the later events for the same set of headliners. It should be read this way:
Exclude the event if there is another available event starting earlier and there is no at least one artist from either event that is not headliner of the other event (i.e. they have the same headliner set).
Edit:
A pretty decent partial-LINQ lazily executed solution could be done in this way:
Firstly, get your query up to the ordered events based on popularity:
var evArtists = Context.Events
.Where(x => x.Stage.Venue.AreaId == 1 && x.StartDateTimeUtc > DateTime.UtcNow && x.IsVerified)
.OrderByDescending(x => x.Headliners.Max(y => y.Popularity));
Secondly, since a ICollection<Artist> can be unordered yet forming equal set, creates an intermediate function to check if two ICollection<Artist> are of identical members:
private bool areArtistsEqual(ICollection<Artist> arts1, ICollection<Artist> arts2) {
return arts1.Count == arts2.Count && //have the same amount of artists
arts1.Select(x => x.ArtistId)
.Except(arts2.Select(y => y.ArtistId))
.ToList().Count == 0; //when excepted, returns 0
}
Thirdly, use the above method to get the unique artists set in the query results, put the results in a List, and fill the List with the number of elements you need (say, 10 elements):
List<Events> topEvList = new List<Events>();
foreach (var ev in evArtists) {
if (topEvList.Count == 0 || !topEvList.Any(te => areArtistsEqual(te.Headliners, ev.Headliners)))
topEvList.Add(ev);
if (topEvList.Count >= 10) //you have had enough events
break;
}
Your result is in the topEvList.
Benefits:
The solution above is lazily executed and is also pretty decent in the sense that you can really break down the logic and check your execution piece by piece without breaking the performance.
Note that using the method above you do not need to refer to the evArtists (which is your large query) other than by its individual element ev. Using full-LINQ solution is possible, yet you may need to refer to evArtists.Any to find the duplicates set of artists (as you do have have memory of what sets has been chosen before) from the original ordered query itself (rather than by simply using its element (ev) one by one).
This is possible because you create a temporary memory topEvList which records what sets have been chosen before and only need to check if the next element (ev) is not among the already selected set of artists. Thus, you do not impair your performance by checking you set of artists against the whole ordered query every time.
Original:
You are almost there actually. What you further need are LINQ GroupBy and First, and put your Take(10) the last:
var query = Context.Events
.Where(x => x.Stage.Venue.AreaId == 1 && x.StartDateTimeUtc > DateTime.UtcNow && x.IsVerified)
.OrderByDescending(x => x.Headliners.Max(y => y.Popularity))
.GroupBy(a => a.ArtistId)
.Select(e => e.First())
.Take(10);
Since in by this query you have sorted your headliner artist:
.OrderByDescending(x => x.Headliners.Max(y => y.Popularity))
Then you only need to group your headliners by ArtistId:
.GroupBy(a => a.ArtistId)
Thus each artist would be having one group. Then next, you only want the first element in the group (supposedly the most popular Event per Artist):
.Select(e => e.First())
And thus you will get all the most popular events per artist. And lastly, among these most popular events per artist, you only want to take 10 of them, thus:
.Take(10);
And you are done!

Convert IQueryable to IOrderedQueryable

I have 2 tables : Items and ItemMetrics. Items contains my items and ItemMetrics contains statistics about those items.
I'm trying to sort a list of Items by the corresponding statistic Weight.
I got it to work using a subquery, but I thought it was a little inefficent and could be optimized...
items.OrderBy(item => (from metric in Context.ItemMetrics where item.ItemId == metric.ItemId select metric.Weight).FirstOrDefault());
...So I am trying to accomplish the same thing using a join...
from item in items join metric in ItemMetrics on item.ItemId equals metric.ItemId orderby metric.Weight select item;
This is working fine in LINQPad. I need to return an IOrderedQueryable for a supplmentary method to do some paging using Skip and Take, but the compiler is telling me the result of this query is an IQueryable.
The only way I can think of explictly implying IOrderedQueryable is wrapping the query in
OrderBy(x => 0)
Is there a better way?
The problem is that an IOrderedQueryable needs to be able to apply a secondary ordering - and by the time you've projected the item/metric pair to just an item, you've lost the primary ordering.
One approach would be to defer the projection until later:
var ordered = items.Join(ItemMetrics,
item => item.ItemId,
metric => metric.ItemId,
(item, metric) => new { item, metric })
.OrderBy(pair => pair.Metric.Weight);
var paged = ApplyPaging(ordered, pageConfiguration); // Whatever
var query = paged.Select(pair => pair.Item);
That's assuming ApplyPaging (or whatever you're using) returns an IQueryable or an IOrderedQueryable.

Getting records in between two records using Linq

I have a list of objects and need to get the list of records from this list. like I have of Countries and I need to get the list of countries which are in between country with name "Australia" and country "Indonasia", the list will not be sorted.
Am using c#.
I tried to use something like, get the index of first and second and then use that to get the list with a for loop, but would be handy if it can be done in single query.
If you do the following:
var elementsBetween = allElements
.SkipWhile(c => c.Name != "Australia")
.Skip(1) // otherwise we'd get Australia too
.TakeWhile(c => c.Name != "Indonasia");
you'll get the result you want without iterating through the list 3 times.
(This is assuming your countries are e.g. Country items with a Name string property.)
Note that this doesn't sort the countries at all - it's unclear from your question whether you want this or not but it's trivial to add an OrderBy before the SkipWhile.
this should do the job
var query = data.SkipWhile(x => x != "Australia").TakeWhile(x => x != "Indonesia")

LINQ: Doing an order by!

i have some Linq to Entity code like so:
var tablearows = Context.TableB.Include("TableA").Where(c => c.TableBID == 1).Select(c => c.TableA).ToList();
So i'm returning the results of TableA with TableB.TableBID = 1
That's all good
Now how can I sort TableA by one of its column? There is a many to many relation ship between the two tables
I tried various ways with no look, for example
var tablearows = Context.TableB.Include("TableA").Where(c => c.TableBID == 1).Select(c => c.TableA).OrderBy(p => p.ColumnToSort).ToList();
In the above case when i type "p." i don't have access to the columns from TableA, presumably because it's a collection of TableA objects, not a single row
How about using SelectMany instead of Select :
var tablearows = Context.TableB.Include("TableB")
.Where(c => c.TableBID == 1)
.SelectMany(c => c.TableA)
.OrderBy(p => p.ColumnToSort)
.ToList();
EDIT :
The expression below returns collection of TableAs -every element of the collection is an instance of TableA collection not TableA instance- (that's why you can't get the properties of the TableA) :
var tablearows = Context.TableB.Include("TableB")
.Where(c => c.TableBID == 1)
.Select(c => c.TableA);
If we turn the Select to SelectMany, we get the result as one concatenated collection that includes elements :
var tablearows = Context.TableB.Include("TableB")
.Where(c => c.TableBID == 1)
.SelectMany(c => c.TableA);
Okay, so now I've taken on board that there's a many to many relationship, I think Canavar is right - you want a SelectMany.
Again, that's easier to see in a query expression:
var tableARows = from rowB in Context.TableB.Include("TableA")
where rowB.TableBID == 1
from rowA in rowB.TableA
orderby rowA.ColumnToSort
select rowA;
The reason it didn't work is that you've got a different result type. Previously, you were getting a type like:
List<EntitySet<TableA>>
(I don't know the exact type as I'm not a LINQ to Entities guy, but it would be something like that.)
Now we've flattened all those TableA rows into a single list:
List<TableA>
Now you can't order a sequence of sets by a single column within a row - but you can order a sequence of rows by a column. So basically your intuition in the question was right when you said "presumably because it's a collection of TableA objects, not a single row" - but it wasn't quite clear what you mean by "it".
Now, is that flattening actually appropriate for you? It means you no longer know which B contributed any particular A. Is there only actually one B involved here, so it doesn't matter? If so, there's another option which may even perform better (I really don't know, but you might like to look at the SQL generated in each case and profile it):
var tableARows = Context.TableB.Include("TableA")
.Where(b => b.TableBID == 1)
.Single()
.TableA.OrderBy(a => a.ColumnToSort)
.ToList();
Note that this will fail (or at least would in LINQ to Objects; I don't know exactly what will happen in entities) if there isn't a row in table B with an ID of 1. Basically it selects the single row, then selects all As associated with that row, and orders them.

Categories

Resources