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

IzzyTwinkly
IzzyTwinkly used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
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

Most Valuable Expert 2018
Distinguished Expert 2018
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

Top Expert 2016
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
Top Expert 2016

Commented:
There are given valid solutions and one correction.

Sara

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial