Why can I not use OrderBy() in this lambda expression? - c#

How do I order the following? The orderBy doesnt recognise the x.Name.
var xRefsNames = db.CrossRefs.Where(x => pgNos.Contains(x.PG))
.Select(x => x.Name)
.Distinct()
.OrderBy(x=>x.Name);

Your select is projecting a different object, probably a string based on the name. You want to just order by x.
var xRefsNames = db.CrossRefs.Where(x => pgNos.Contains(x.PG))
.Select(x => x.Name)
.Distinct()
.OrderBy(x=>x);

Related

How to convert linq query to non-query expression?

I use EF6, I have this linq to entity query:
from s in SensorObservationEntities.SensorsMeasures
group s by s.SensorUnitId into g
let latest = g.OrderByDescending(s => s.MeasureDate).FirstOrDefault()
select latest
How can I convet it to non-query expression?
You mean method syntax :
SensorObservationEntities.SensorsMeasures.GroupBy(g => g.SensorUnitId)
.Select(y => y.OrderByDescending(x => x.MeasureDate).FirstOrDefault());
If you want to convert this to the method syntax version, you can do this step by step. I like to start at the end and work through to the beginning:
select to Select defines the source:
.Select(g => g.OrderByDescending(s => s.MeasureDate).FirstOrDefault());
group is GroupBy:
.GroupBy(s => s.SensorUnitId)
.Select(g => g.OrderByDescending(s => s.MeasureDate).FirstOrDefault());
from the source
SensorObservationEntities.SensorsMeasures
.GroupBy(s => s.SensorUnitId)
.Select(g => g.OrderByDescending(s => s.MeasureDate).FirstOrDefault());

How to use LINQ to adjust result?

From this LINQ:
var inspectionItems = inspArchive.Select(x => x.InspectionItems);
I get this result in inspectionItems :
My question is how can I make using LINQ in elegant way to make from inspectionItems result above one array distincted by Id.
Like that:
You want the SelectMany() LINQ method:
var inspectionItems = inspArchive.SelectMany(x => x.InspectionItems);
If you only want distinct items by a particular property, then you can either implement an equality comparer to see if your inspection classes are equal, then call .Distinct(myInspectionEqualityComparer) at the end of your method chain, or you can do this:
var distinctInspectionItems = inspArchive.SelectMany(x => x.InspectionItems)
.GroupBy(i => i.Id)
.Select(group => group.First());
Without seeing more of your code, I think you want to use SelectMany and Distinct ?
var inspectionItems = inspArchive.SelectMany(x => x.InspectionItems).Distinct();
The question is unclear, but check if this works for you:
var inspectionItems = inspArchive.SelectMany(x => x.InspectionItems)
.GroupBy(x => x.ID)
.Select(g => g.First())
.ToArray();

Ordered grouping without Dictionary

I am grouping train trips according to the coal mines they service, and then dealing with the each group starting with the most populous.
List<List<Trip>> tripsByMine = trips.GroupBy(x => x.demand.Mine)
.ToDictionary(x => x.Key, x => x.ToList())
.Values.OrderByDescending(x => x.Count)
.ToList();
It seems to me that the ToDictionary call is superfluous because I just want the Values. Is there a shorter way of getting the same result?
Try this
List<List<Trip>> tripsByMine2 = trips.GroupBy(x => x.demand.Mine)
.Select(x => x.ToList())
.OrderByDescending(x => x.Count)
.ToList();
Possible solution:
List<List<Trip>> tripsByMine = trips.GroupBy(x => x.demand.Mine)
.Select(x => new {Key=x.Key, Values=x,Count=x.Count()})
.OrderByDescending(x => x.Count)
.Select(x=>x.Values.ToList())
.ToList();

Multiple GroupBy in 1 linq expression

I cannot seem to combine 2 GroupBy statements in 1 linq expression..
For now i'm doing something like this:
double maxInvestment = 0;
foreach (var playerAction in TotalUserActions.GroupBy(p => p.Player))
{
var MaxInvestmentPerPlayer = playerAction.GroupBy(p => p.RoundId)
.Select(p => p.LastOrDefault())
.Sum(p=> p.BetSize);
if(MaxInvestmentPerPlayer > maxInvestment)
maxInvestment = MaxInvestmentPerPlayer;
}
What I would like to do is something like this...
double maxInvestment = TotalUserActions.GroupBy(p => p.Player)
.GroupBy(p => p.RoundId)
.Select(p => p.LastOrDefault())
.Sum(p=> p.BetSize);
But that wont work.. Can someone help me on this?
Thanks!
Looks like this is what you want, the key takeaway being the inner query is wrapped in an outer call to Select():
var maxInvestment = TotalUserActions.GroupBy(p => p.Player)
.Select(g => g.GroupBy(x => x.RoundId)
.Select(x => x.LastOrDefault())
.Sum(x => x.BetSize))
.Max();
I do question your use of LastOrDefault() though as, since you have not specified any ordering, you may as well use FirstOrDefault() and save the hassle of skipping to the last element.

LINQ OrderBy Name ThenBy ChildrenCollection.Name

Is there any way in LINQ to do an OrderBy and then do a ThenBy with the ThenBy using the children of the parent object to do the secondary ordering?
_repository.GetActiveDepartmentGroupsWithDepartments().OrderBy(c => c.DepartmentGroupName).ThenBy(c => c.Departments.OrderBy(d => d.DepartmentName))
In the above case, c.Departments is an EntityCollection.
BTW: When I try the above and then do a ToList() on it, I get this error:
DbSortClause expressions must have a type that is order comparable.
Parameter name: key
Thanks in advance for any help or guidance.
It seems like you're trying to get a list of all departments ordered by group then department name. If so, then you probably want to do something like this:
var res = from c in _repository.GetActiveDepartmentGroupsWithDepartments()
from d in c.Departments
orderby c.DepartmentGroupName, d.DepartmentName
select d;
Or in method syntax:
var res = _repository.GetActiveDepartmentGroupsWithDepartments()
.SelectMany(c => c.Departments, (c,d) => new { c, d })
.OrderBy(x => x.c.DepartmentGroupName)
.ThenBy(x => x.d.DepartmentName)
.Select(x => x.d);
Since Deparment is a collection, you have to transform it to a scalar to use it for sorting.
One option is to select a single entity to in the collection, e.g. the name of the first department:
_repository.GetActiveDepartmentGroupsWithDepartments()
.OrderBy(c => c.DepartmentGroupName)
.ThenBy(c => c.Departments
.OrderBy(d => d.DepartmentName)
.FirstOrDefault()
.DepartmentName
)
Another option is to order by a property of the collection itself, e.g. the number of departments:
_repository.GetActiveDepartmentGroupsWithDepartments()
.OrderBy(c => c.DepartmentGroupName)
.ThenBy(c => c.Departments.Count())

Categories