How to fix my LINQ expressions with Distinct() in it?

1 day ago 3
ARTICLE AD BOX

Well, this wasn't obvious until I brought it into Visual Studio to let the JIT and Intellisense errors tell me what was going on.

Linq Distinct returns an IEnumerable, which doesn't have a ForEach method. You have to add ToList after the Distinct and before ForEach, and then it doesn't throw errors anymore.

számlák.OrderBy(x => x.PályázatKód).Select(x => x.PályázatKód).Distinct().ForEach(x => sw.Write($"{x}\n")); }

becomes

számlák.OrderBy(x => x.PályázatKód).Select(x => x.PályázatKód).Distinct().ToList().ForEach(x => sw.Write($"{x}\n")); }

You can also rearrange your Linq and use a different method to simplify and potentially speed up your code. This allows you to get your distinct string before you do anything, which should simplify everything else after it.

számlák.DistinctBy(x => x.PályázatKód).Select(x => x.PályázatKód).OrderBy(x => x).ToList().ForEach(x => sw.Write($"{x}\n"));

There's a few other things I'd like to suggest. In your model, you don't need the private variables. You can declare your properties with just a blank getter and setter, and C# does the rest. This also means that your don't need to use `this.` to reference your data, you just use the property name.

public string PályázatKód { get => pályázatKód; set => pályázatKód = value; }

becomes

public string PályázatKód { get; set; }

And adding the 0 padding to the front of the beker variable can be done without the loop.

beker = new string('0', 3 - beker.Length) + beker;

I know you didn't ask for all that extra stuff, but refactoring code is pretty much obligatory for me at this point. I don't intend to step on toes, just suggest ways to improve people's understanding of a very complex language (C#) and framework (.Net). Granted, you may be using a different framework version, so some of this might not work for you, at least on this project. But you might remember it the next time you do something similar and can use it then.

One last thing: please use explicit datatypes. Using var is now considered a code smell. Visual Studio can let you know what datatype to use, and I'm sure other IDEs will do something similar, if you can't figure it out yourself. And sometimes it's not easy to figure out.

Read Entire Article