How can I sort by multiple fields in LINQ? - linq

how can I do multiple sort in
return (from p in _db.Pages where p.int_PostStatusId == 2 select p).OrderByDescending(m => m.int_SortOrder);
i want to do order by by int_PageId as well? first by int_SortOrder then by int_PageId

Use either ThenBy or ThenByDescending to order the result of an OrderBy or OrderByDescending:
return (...)
.OrderByDescending(m => m.int_SortOrder)
.ThenBy(m => m.int_PageId);
Or using the query syntax:
orderby p.int_SortOrder descending, p.int_PageId

Related

Linq order based on some other column condition

I have a list having columns like ID, Name, Country, State
The order statement needs to be in following way
.ToList().OrderByDescending(first=>t.Country).ThenBy(**if state=='GA' then ID else Name**)
My question is how to do this ThenBy clause based on some other column condition?
So it's correct that you don't want to order in the database but in memory? Even then you should not use ToList before you start ordering but AsEnumerable and add ToList at the end.
var resultList = yourQuery.AsEnumerable() // Linq-To-Objects as desired
.OrderByDescending(x => x.Country)
.ThenBy(x => x.state == "GA" ? x.ID.ToString() : x.Name)
.ToList();

Linq orderby and distinct

I have a table set up as follows:
Section SectionOrder
Sect1 1
Sect2 2
Sect3 3
Sect3 3
Sect1 1
Sect2 2
I need to pull out distinct sections in correct section order. Here is the linq that I'm using, but it's not putting them in the correct order for some reason.
var myVar = (from x in context.Documents
orderby x.SectionOrder ascending
select x.Section).Distinct();
I then want to be able to loop through myVar and put each item in a list as follows:
foreach (var t in myVar)
{
listOfDocTypeSections.Add(t);
}
The ordering of OrderBy and Distinct matters: while OrderBy produced an ordered sequence, Distinct doesn't. You need to put Distinct first, and then use OrderBy. However, since you take Distinct on one attribute, and order on the other attribute, you need to do it differently:
var myVar = context
.Documents
.GroupBy(x => x => x.Section) // This replaces Distinct()
.OrderBy(g => g.FirstOrDefault().SectionOrder) // There will be no default
.Select(g => g.Key);
This approach replaces Distinct with GroupBy, and orders on the first SectionOrder item of a group. You can change this sorting strategy to sort on some other item within the Section, say, Min or Max value of SectionOrder:
var myVar = context
.Documents
.GroupBy(x => x => x.Section)
.OrderBy(g => g.Max(x => x.SectionOrder))
.Select(g => g.Key);

LInq Order By and Order By Desc

I am using "Linq" to filter list of objects and to sort them, like
myList.Where(x => x.Item!= "SF" && x.AdSize == minadSize)
.OrderBy(x => x.ManufacturingDate)
.OrderBy(x=>x.ExpiryDate);
I doubt whether i am doing it right or not that is if i want to "sorting" on multiple fields then is it necessary to use multiple Order By clause cant it be done with single "OrderBy"
Don't use multiple OrderBy calls - use OrderBy followed by ThenBy:
var query = myList.Where(x => x.Item!= "SF" && x.AdSize == minadSize)
.OrderBy(x => x.ManufacturingDate)
.ThenBy(x => x.ExpiryDate); // Could add more ThenBy calls
If you use OrderBy twice, it will reorder the already-ordered-by-date list by expiry-date, whereas I assume you only want to order by expiry date for items with an equal manufacturing date, which is what the above does.
Obviously there's a ThenByDescending method too. For example:
var query = people.OrderBy(x => x.LastName)
.ThenBy(x => x.FirstName)
.ThenByDescending(x => x.Age)
.ThenBy(x => x.SocialSecurity);

complex orderby that links to another table

I have the following query to start with:
var query = from p in db.Products
from pc in p.NpProductCategories
where pc.CategoryId == categoryId
select p;
I'm applying some more filtering on it and in the end I want to sort the results:
if (orderBy == ProductSortingEnum.Name)
query = query.OrderBy(x => x.Name);
else
query = query.OrderBy(............);
My big problem (coming from not knowing linq too good) is the ELSE here. How can I sort results by a column that is not in the current result set? I would like to somehow link to another linq query in the orderby. The sorting I'm trying to achive is to link to NpProductVariants query using the ProductId to match between NpProductVariant and Products
and sort by the Price of the NpProductVariant
Assuming you have the relationship set up in the dbml...
For one to one (and many to one):
query = query.OrderBy(p => p.NpProductVariant.Price);
For one to many:
query = query.OrderBy(p => p.NpProductVariants.Select(v => v.Price).Max());
Also:
var query =
from p in db.Products
where p.NpProductCategories.Any(pc => pc.CategoryId == categoryId)
select p;
I think you can hook your Join to your query as long as it is returning the same thing. So maybe something like (I'm not 100 % sure since I haven't tried it):
query = from i1 in query
join i2 in query2 on i1.PropertyToJoin equals i2.PropertyToJoin
orderby i1.OrderProp1, i2.OrderProp2
select i1;
But I think it might be a good idea to check the generated sql so it is still effective.

linq multiple order DESCENDING

.OrderBy(y => y.Year).ThenBy(m => m.Month);
How to set descending order?
EDIT:
I tried this:
var result = (from dn in db.DealNotes
where dn.DealID == dealID
group dn by new { month = dn.Date.Month, year = dn.Date.Year } into date
orderby date.Key.year descending
orderby date.Key.month descending
select new DealNoteDateListView {
DisplayDate = date.Key.month + "-" + date.Key.year,
Month = date.Key.month,
Year = date.Key.year,
Count = date.Count()
})
//.OrderBy(y => y.Year).ThenBy(m => m.Month)
;
And it seems working. Is it wrong to use orderby twice like I used it here?
You can get the descending ordering by using a different pair of methods:
items.OrderByDescending(y => y.Year).ThenByDescending(m => m.Month);
Using LINQ query, you can write:
from date in db.Dates
orderby date.Key.year descending, date.Key.month descending
select new { ... }
The trick is that you need only one orderby clause - if you add multiple of these, the list will be re-sorted each time. To sort elements that have the first key equal using another key, you need to separate them using , (orderby is translated to OrderBy or OrderByDescending while , is translated to ThenBy or ThenByDescending).

Resources