简体   繁体   中英

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.

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM