LINQ sort collection with IF statement [duplicate] - c#

This question already has answers here:
Multiple "order by" in LINQ
(7 answers)
Closed 4 years ago.
I want to sort the collection before processing. I used to use this method:
foreach (var item in Items.OrderBy(i => i.property1))
{
...
}
Now i need to sort it by property2, if property values is equals between two items. Is there any method to do that logic via LINQ expression?

Is this what you're after?
foreach (var item in Items.OrderBy(i => i.property1).ThenBy(i => i.property2))
{
...
}

Related

How to replace foreach with linq [duplicate]

This question already has answers here:
Update all objects in a collection using LINQ
(18 answers)
Closed 16 days ago.
foreach (var item in items)
{
item.category = "All Items";
}
How to replace the above foreach with Linq.
I have tried with following code, but it returns null for the item
_ = items.Select(x => x.item = "All Items")
Note : items is of type IEnumerable<ItemList>
linq is an example of functional programming - in general it does not change the input data it reads it in and outputs new data
you can do this (assuming you have a List to start with)
items = items.Select(item=>new {category="All Items", x=.., y=..}).ToList()
wher x and y are the other fields in ItemList

Extracting a list from a list LINQ [duplicate]

This question already has answers here:
Using LINQ, select list of objects inside another list of objects
(2 answers)
Closed 1 year ago.
I am trying to extract a list of Goals from within a list of Students using this method
public List<Goal> GetGoalsForTeacher(int userId)
{
var students = GetStudentsForTeacher(userId);
var result = students.Select(e => e.Goals).ToList();
return result
}
However, I need it to return a List, but it is returning a List<IList>. Has anyone any idea on how I would convert this or make it a List initially?
You're looking for the SelectMany() method.
var result = students.SelectMany(e => e.Goals).ToList();

Multiple OrderBy not ordering correctly [duplicate]

This question already has answers here:
Multiple "order by" in LINQ
(7 answers)
Closed 3 years ago.
I'm trying to order by WeekId, then Order in my SQL table (end result should have workouts together by id, then ordered by the order specified), yet it is giving the wrong order. Is there something wrong with my LINQ statement?
private List<Workout> GetWorkouts(int id)
{
return new OPPDBContext().Workouts
.Where(p=>p.ClientId == id).OrderBy(p => p.Order).OrderBy(p => p.WeekId).ToList();
}
The table:
The results:
Expected results:
Lat Pulldowns
Squats
Lat Pulldowns
Squats
Reverse Lunges
That's because the second .OrderBy replaces the first .OrderBy (you are sorting by ClientId, and then effectively discard that to sort by WeekId).
You need to use .OrderBy(...).ThenBy(...) instead:
return new OPPDBContext().Workouts.Where(p=>p.ClientId == id).OrderBy(p => p.Order).ThenBy(p => p.WeekId).ToList();
OrderBy docs
ThenBy docs

Transform foreach to LINQ [duplicate]

This question already has answers here:
LINQ equivalent of foreach for IEnumerable<T>
(22 answers)
Closed 3 years ago.
I have two collections, both contain objects.
First one is IList and the second one is Dictionary.
I need to traverse through IList and if the condition is filled then activate method from the certain object which is stored in Dictionary.
The current situation is like this:
foreach (MyObject mo in MyListOfObjects)
{
if (mo.Active == myStatus.Enabled)
{
DictList[mo.ID].Start();
}
}
So far i've done this:
var r = MyListOfObjects.Where(mo => mo.Active == myStatus.Enabled);
But I have no idea how to include in this DictList[mo.ID].Start();
Not a great use of linq, but you could filter the list using linq then loop through it.
var itemsToStart = MyListOfObjects.Where(mo => mo.Active == myStatus.Enabled)
.Select(mo=> DictList[mo]); //or ToList() if you intend to re-iterate
foreach (var itemToStart in itemsToStart) {
itemToStart.Start();
}
If anything at all, just remove the inner if
foreach (MyObject mo in MyListOfObjects.Where(x => x.Active == myStatis.Enabled))
{
DictList[mo.ID].Start();
}
But that is all you should do - it is perfectly readable and maintainable.
MyListOfObjects.Where(mo => mo.Active == myStatus.Enabled).ToList().ForEach(mo => DictList[mo.ID].Start());
ForEach is found: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.foreach?view=netframework-4.7.2

What does this line mean in C# r => r.Item1? [duplicate]

This question already has answers here:
C# Lambda expressions: Why should I use them?
(17 answers)
Closed 5 years ago.
r => r.Item1 == dFName
Its part of this line
dFName = PropertyUtil.GetName<kUpdate>(r => r.Resolution);
fld2Lup = map.DTField2LookupMap[domType].First(r => r.Item1 == dFName );
That is essentialy..
Return the First item of the "DTField2LookupMap[domType]" collection where the items property "Item1" is equal to dfName
this is a lambda expression: https://msdn.microsoft.com/en-us/library/bb397687.aspx

Categories