NoviceMe
NoviceMe

Reputation: 3256

Remove only one element from string array using linq

I have following code:

string[] s = {"one", "two", "three", "two", "Four"}; 
s = s.Where(x => x!="two").ToArray(); 

I want to remove "two" only once using linq is there a way to do this? Code i tried above removes both "two" elements from the array.

Upvotes: 0

Views: 980

Answers (2)

GGO
GGO

Reputation: 2748

If you just want to remove the first occurrence :

var t = s.ToList();
t.Remove(value);
s = t.ToArray();

Otherwise it's the .Distinct() function

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460098

Well, maybe you want to remove duplicates in general, then it's very simple:

s = s.Distinct().ToArray();

Otherwise you can use GroupBy:

s = s.GroupBy(str => str).SelectMany(g => g.Key != "two" ? g : g.Take(1)).ToArray();

This allows duplicates in general, but two must be unique.

Upvotes: 1

Related Questions