0

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.

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.