Reputation: 3256
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
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
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