Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove repeating elements in an array using LINQ?remove an element if its repeating?

Tags:

c#

.net

linq

int [] n=new int[10]{2,3,33,33,55,55,123,33,88,234};
output=2,3,123,88,234;

use LINQ i can do it using two for loops by continuously checking.but i need a more simple way using LINQ

its not removing duplicates.. removing duplicates by distinct will give = 2,3,123,33,55,88,234 my output should be = 2,3,123,,88,234;

like image 767
Lijo Avatar asked May 09 '26 20:05

Lijo


2 Answers

I combined your grouping idea and matiash's count. Not sure about its speed.

var result = n.GroupBy(s => s).Where(g => g.Count() == 1).Select(g => g.Key);

Update: i have measured the speed and it seems the time is linear, so you can use it on large collections

like image 66
Dmitrii Dovgopolyi Avatar answered May 12 '26 10:05

Dmitrii Dovgopolyi


var result = n.Where(d => n.Count(d1 => d1 == d) <= 1);

This reads: only take those elements that are present at most 1 times in n.

It's quadratic though. Doesn't matter for short collections, but could possibly be improved.

EDIT Dmitry's solution is linear, and hence far better.

like image 30
matiash Avatar answered May 12 '26 11:05

matiash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!