2

Example: Array1.Intersect(Array2) checks for only distinct elements.

Is there an elegant way using linq to get the result which contains even duplicates? The result should be case-insensitive. Thanks.

2
  • Can you make an example with desired input and output? Commented Apr 29, 2013 at 10:43
  • input: string[] Arr1= new string[] { "a","a", "b", "y" }; string[] Arr2= new string[] {"s", "a", "z", "b", "c", "a"}; Output {"a", "a", "b"} but not {"a", "b"} Commented Apr 29, 2013 at 10:47

2 Answers 2

4

Not as efficient but clear:

var inboth = Array1.Where(Array2.Contains);

Edit according to your case-insensitive comment:

inboth = Array1.Where(s => Array2.Contains(s, StringComparer.OrdinalIgnoreCase));
Sign up to request clarification or add additional context in comments.

5 Comments

converting Array2 to a HashSet might make things more efficient if there are enough elements in Array1, either way this works.
Thanks Tim. However I forgot to mention that the result should also contain case-insensitive elements.
@user1191177: You haven't even told that the arrays are String[]. However, give me a moment.
you could consider using the current culture over ordinal, I know ordinal would be faster but in some cultres things change more when you shift case (I think.) The HashSet option is still available, as shown in my improved answer.
Most people want to compare culture-agnostic and even if he wants to take the current culture into account, as far as i know Ordinal passes the turkey test since it behaves like ToUpper(instead of the dangerous ToLower).
0

after your comment,

var secondSet = new HashSet<string>(
    array2,
    StringComparer.CurrentCultureIgnoreCase);

var intersectSequence = array2.Where(secondSet.Contains);

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.