MikeInvise
❔ Using Linq to Add or Update Score in Highscore List Object
This is what I have
public class Highscore
{
public string StringValue { get; set; }
public int IntValue { get; set; }
public Highscore(string stringValue, int intValue)
{
StringValue = stringValue;
IntValue = intValue;
}
}
public static class HighscoreExentions
{
public static IEnumerable<Highscore> AddOrUpdate(
this IEnumerable<Highscore> highscores, string name, int value=0)
{
if (highscores.Any(x => x.StringValue == name))
{ highscores.Where(x => x.StringValue == name).Select(y => y.IntValue += value); }
else { highscores.ToList().Add(new Highscore(name, value)); }
return highscores;
}
}
Before I wrote this post, I didn't even have that, because I was trying to do it without an extension method, or as minimally as possible. I thought I could cast or project a propsed value and use something like DefaultIfEmpty or Where to add or update. This looks like it loops through the list several times, and in that several more times. I want to be as efficient as possible, as the highscore list could end up be hundreds, of entries long.
I had an issue in another part of the project, where I was looping through a list inside another loop, both lists were several hundred entries long, and I was originally doing that to select items that matched each other, and then do something with that. That loop inside a loop then perform, I found was taking 40 seconds, and I have a Ryzen 7 3700 8 Core CPU.
10 replies