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
Related
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();
This question already has answers here:
A method to count occurrences in a list
(7 answers)
Closed 2 years ago.
do you know how to check how many times an item exists in a c# list? I've tried with
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(1);
numbers.Add(2);
numbers.Add(2);
Console.WriteLine(numbers.Count);
but it's count of items in list (4 items) but i want that there are two "1" and two "2". Do you know how to do this? Please help me.
You can create a grouping and then create a dictionary from it using LINQ:
Dictionary<int, int> numberFrequency = numbers
.GroupBy(n => n)
.ToDictionary(g => g.Key, g => g.Count());
Then to find out how many times 4 occurred, you can check like so:
int toFind = 4;
if (!numberFrequency.TryGetValue(toFind, out int frequency))
{
frequency = 0;
}
Console.WriteLine($"{toFind} occurred {frequency} time(s).");
Or you can loop through:
foreach (KeyValuePair<int, int> kv in numberFrequency)
{
Console.WriteLine($"{kv.Key} occurred {kv.Value} time(s).");
}
Docs for GroupBy
Docs for ToDictionary
You might also need OrderBy or OrderByDescending.
Try it online
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
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))
{
...
}
This question already has answers here:
C# Linq .ToDictionary() Key Already Exists
(3 answers)
Closed 9 years ago.
I have the following LINQ query that I am using to query a datatable and populate a dictionary, but it keeps throwing the error:
System.ArgumentException: An item with the same key has already been
added.
I am new to LINQ and cannot figure out the proper way to write this.
Can someone please assist?
var neworderGroupDict = (from m in KMVData.AsEnumerable()
select new
{
datakey = m.Field<string>("OrderNumber"),
datavalue = m.Field<int>("OrderGroup")
}).Distinct().ToDictionary(n => n.datakey, n => n.datavalue);
That means your data key (in this case combination of OrderNumber and OrderGroup) is not unique. Happens because .Distinct() wont filter duplicates without IEqualityComparer for your type.
Edit:
One way of fixing that and preserving all datavalues for OrderNumber is first grouping by and then converting it to dictionary:
var neworderGroupDict = (from m in KMVData.AsEnumerable()
select new
{
datakey = m.Field<string>("OrderNumber"),
datavalue = m.Field<int>("OrderGroup")
}).GroupBy(x => x.datakey)
.ToDictionary(g => g.Key, g => g.ToList());
Try DistinctBy of MoreLinq.
Then you can use ToDictionary without any problems.