[SOLVED] The Linq Distinct() usage | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

[SOLVED] The Linq Distinct() usage

Hi SoloLearners, In attempt to answer a question on how to remove duplicates from array, I searched and found that it was possible by the use of HashSet and Linq. But it seems I wasn't using Linq the right way. It doesn't remove duplicates from the string array. What did I do wrong? The code (Edited) https://code.sololearn.com/c2t6vGxCg1lM/?ref=app Thank you in advance 🙏

16th Dec 2021, 3:14 PM
Ipang
6 Answers
+ 2
You are. Maybe, the variable you want to print in the end is "query" and not "strArray".
16th Dec 2021, 3:32 PM
Anya
Anya - avatar
+ 2
Ipang Like in the Microsoft docs example? You need to loop over strArray and print in the format that you want.
16th Dec 2021, 3:50 PM
Anya
Anya - avatar
+ 2
Ipang I don't think it is possible. Seems that Linq just returns distinct elements without change the original object. You need to assign to a variable to get the result.
16th Dec 2021, 4:12 PM
Anya
Anya - avatar
+ 1
Anya You're right ... Thanks. One more question. What do I do to also see the effect of Distinct() on <strArray>. I mean, the example using HashSet made changes to the array, how to do that with Linq?
16th Dec 2021, 3:41 PM
Ipang
+ 1
Anya no ... I want the Distinct() filtered items to also reflect in <strArray>. The docs example shows how to print the <query> but I want to see the change to reflect in the array like the one from HashSet example. Is it possible? or that's just how Linq works?
16th Dec 2021, 3:55 PM
Ipang
+ 1
Okay Anya I figured I'd just glue the <query> to get the filtered string back ... Thanks for the correction and enlightenment 🙏
16th Dec 2021, 4:16 PM
Ipang