How do I compare IOrderedEnumerable<char> in C#?

Hi,

I have the following code to check if two string are the same after they are re-ordered.
I want to use LINQ and this is what I did.
when I print s1 and s2 using foreach...they are both "eilnst". But it returns "false".

How can I correct this?

static void Main(string[] args)
        {
            string str1 = "Silent";
            string str2 = "Listen";
            Console.WriteLine(areEqual(str1, str2));
            Console.Read();
        }
        
        public static bool areEqual(string str1, string str2)
        {
            var s1 = str1.ToLower().OrderBy(x => x);
            var s2 = str1.ToLower().OrderBy(x => x);
            foreach (var item in s1)
            {
                Console.Write(item);

            }
            Console.WriteLine();
            foreach (var item in s2)
            {
                Console.Write(item);
            }
            Console.WriteLine();

            return  str1.ToLower().OrderBy(x => x)==(str1.ToLower().ToList().OrderBy(x => x));          
        }

Open in new window

IzzyTwinklyAsked:
Who is Participating?
 
käµfm³d 👽Connect With a Mentor Commented:
You are comparing two IEnumerable instances by reference. These would never be equal unless they are the exact same reference. You could try using the SequenceEqual method:

return Enumerable.SequenceEqual(str1.ToLower().OrderBy(x => x), str1.ToLower().OrderBy(x => x));

Open in new window

0
 
Chris StanyonConnect With a Mentor Commented:
Alternatively, you could convert your IEnumerable<char> to a string and compare the results:

var s1 = string.Concat(str1.ToLower().OrderBy(x => x).TakeWhile(char.IsLetter));
var s2 = string.Concat(str2.ToLower().OrderBy(x => x).TakeWhile(char.IsLetter));

return s1 == s2;

Open in new window

0
 
sarabandeConnect With a Mentor Commented:
           var s1 = str1.ToLower().OrderBy(x => x);
            var s2 = str1.ToLower().OrderBy(x => x);
there is a typo. you were using str1 for both statements.  (it was corrected in the code Chris has posted).

Sara
1
 
sarabandeCommented:
There are given valid solutions and one correction.

Sara
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.