vic
vic

Reputation: 227

c# how to check if list of Items are in Alphabetical order or not

I have list of 10 Iwebelements . i've stored their text into another list(As i just need to check that all 10 are in Alphabetical Order)

Can any one please tell me how to do that .

(Below code will get the list of all elements and with Foreach i'm getting their text and adding them into X list)

 IList<IWebElement> otherSports = Driver.FindElements(By.CssSelector(".sports-buttons-container .other-sport .sport-name"));
        List<string> x = new List<string>();

        foreach (var item in otherSports)
        {
            string btnText = item.Text.Replace(System.Environment.NewLine, "");
            x.Add(item.Text.Replace(System.Environment.NewLine, ""));
        }

Note:- I dont want to sort the list . I just want to see if all items in List X is in Alphabetical order.

Any Help would be appreciated.

Upvotes: 2

Views: 9508

Answers (2)

Cheng Chen
Cheng Chen

Reputation: 43523

You can use StringComparer.Ordinal to check if two strings are in alphabetical order.

var alphabetical = true;
for (int i = 0; i < x.Count - 1; i++)
{
    if (StringComparer.Ordinal.Compare(x[i], x[i + 1]) > 0)
    {
        alphabetical = false;
        break;
    }
}

An alternative solution if you prefer LINQ(but less readable, IMO)

var alphabetical = !x.Where((s, n) => n < x.Count - 1 && StringComparer.Ordinal.Compare(x[n], x[n + 1]) > 0).Any();

EDIT since you are generating the list your self, you can add solution 1 into your code when the list is created, that's more efficient.

IList<IWebElement> otherSports = Driver.FindElements(By.CssSelector(".sports-buttons-container .other-sport .sport-name"));
List<string> x = new List<string>();
var alphabetical = true;
string previous = null;

foreach (var item in otherSports)
{
    string btnText = item.Text.Replace(System.Environment.NewLine, "");
    var current = item.Text.Replace(System.Environment.NewLine, "");
    x.Add(current);

    if (previous != null && StringComparer.Ordinal.Compare(previous,current) > 0)
    {
        alphabetical = false;
    }
    previous = current;
}

Upvotes: 3

Vova Bilyachat
Vova Bilyachat

Reputation: 19474

I would do it like that

 [TestMethod]
 public void TestOrder()
 {
     IList<IWebElement> otherSports = Driver.FindElements(By.CssSelector(".sports-buttons-container .other-sport .sport-name"));
     var x = otherSports.Select(item=>item.Text.Replace(System.Environment.NewLine, ""))
     var sorted = new List<string>();
     sorted.AddRange(x.OrderBy(o=>o));
     Assert.IsTrue(x.SequenceEqual(sorted));
 }

So this method will fail untill list x list is ordered alphabetically

Upvotes: 2

Related Questions