Lijo
Lijo

Reputation: 6778

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

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;

Upvotes: 3

Views: 320

Answers (2)

matiash
matiash

Reputation: 55340

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.

Upvotes: 4

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

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

Upvotes: 6

Related Questions