How to use Linq to compare strings in array and get different results

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
Hello:
I have strings in an array. Like this:
string[] old_houses = { "0-0", "0-0", "0-0" };
string[] new_houses = { "0-0", "1-0", "0-1" };
I want to write a function, which will generate the following results:
If the digit before dash ("-") in new_houses is more than the digit before dash ("-") in old_houses, then generate 1 at the corresponding position.
If the digit after dash ("-") in new_houses is more than the digit after dash ("-") in old_houses, then generate -1 at the corresponding position.
If the digits before and after dash ("-") in new_houses are the same for the digits in old_houses, then generate 0 at the corresponding position.
In my example data, I want to have a result like this:
int[] result = { 0, 1, -1 };
I want to use Linq to do this.
I have to following code:

var results =
new_houses.Zip(old_houses, (a, b) => String.Compare(a, b, StringComparison.Ordinal));


But the results are always: { 0, 1, 1 }. How I can generate a -1 for the last string pairs?

If I change the code, like this:

var results =
old_houses.Zip(new_houses, (a, b) => String.Compare(a, b, StringComparison.Ordinal));

Then the results are always: {0, -1, -1}. I can't generate a 1 for the second string pairs. I think I can do this with a big loop to split the string and compare each character to get the results, but I want to write some LINQ code to do this.
By the way, I am using Visual Studio 2019 Version 16.3.4, I wish to use new features in C#.
Please advice!

Continue reading...
 
Back
Top