C
C#2y ago
Velcer

❔ Get collection of a groupBy based on key.

I have a list of KeyValuePairs <ushort, ushort> I am attempting to group the list by the key,
so myNewCollection = list.OrderBy(k => k.key);

now we step into a foreach loop
foreach (var player in players)
{
// TO DO : Get all items from myNewCollection where key is player.Id
// Iterate new collection
}
so myNewCollection = list.OrderBy(k => k.key);

now we step into a foreach loop
foreach (var player in players)
{
// TO DO : Get all items from myNewCollection where key is player.Id
// Iterate new collection
}
csharp What I am having trouble with is understanding the proper, efficient way to get all items of myNewCollection where the key is my playerId.
10 Replies
Velcer
Velcer2y ago
I could just do inside my player loop, foreach (var item in list.Where(s => s.Key == player.Id)) However I believe that by first doing orderBy outside my player loop, I am limiting the overall amount of iterations or at least that is my hope. Correct me if I am wrong.
Saber
Saber2y ago
ordering is going to be more inefficient than just applying a simple where filter.
Velcer
Velcer2y ago
I see. So it is most practical then to just have the where filter inside my player loop? There is perhaps no way to reduce the iterations more than that?
canton7
canton72y ago
ToLookup?
Saber
Saber2y ago
you could convert that list to a lookup.
var lookup = list.ToLookup(x => x.Key);
var lookup = list.ToLookup(x => x.Key);
and accessing the list related to the player would be lookup[player.Id]
Velcer
Velcer2y ago
👀 I've never heard of this before Thank you!!
canton7
canton72y ago
(I take that back - missed you were looping over players)
Velcer
Velcer2y ago
The idea is to do an initial iteration for sorting, before my player loop ah, thank you. I think ToLookup is what I needed
canton7
canton72y ago
Yep
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.