pfinferno
pfinferno

Reputation: 1945

Using LINQ to compare strings alphabetically

I have a collection of objects. Each object has a string property. I'm trying to get a list of those objects where the string is alphabetically before or after a specified string.

Here's an example of what I mean: I have four objects with string properties of apple, banana, carrot, and dirt. The specified string I use is c. I want to use LINQ to return the first two objects with string properties of apple and banana. As a bonus, the ability to include carrot would be nice as well in the same statement rather than use a separate LINQ query for ==.

Here's what I've tried (and variations of it):

var query = from feature in features
            where String.Compare(feature.ColumnValues[selectedField], stringToCompare, StringComparison.OrdinalIgnoreCase) < 0
            select feature;

Where features is my collection.

This isn't returning the correct objects though. It's returning objects that come both before and after alphabetically.

Edit: Can't post the full collection since it's thousand of objects, but the strings being compared to are all locations. For example, In US, Maryland, Near Texas, etc.

A Feature object has a Dictionary<string, string> called ColumnValues. The Key value, which is my selectedField is LOCATION. The Value for that Key is what I'm comparing my stringToCompare to, for each Feature.

Edit 2: The problem seemed to be with casing.

Upvotes: 1

Views: 1237

Answers (1)

ashish
ashish

Reputation: 2358

I tried the code you have provided above.You can use the following for filtering and sorting list:

    public class Feature
    {

        public int Id { get; set; }
        public string ColumnValues { get; set; }
    }

  var features = new List<Feature> { new Feature {Id=1,ColumnValues="carrot" } ,
                 new Feature {Id=1,ColumnValues="dirt" },
                  new Feature {Id=1,ColumnValues="banana" }, new Feature {Id=1,ColumnValues="apple" }
            };

  string strToComapre = "c";
  int lenOfString = 1;

 var query=(from feature in features
                  where String.CompareOrdinal(feature.ColumnValues, 0, strToComapre, 0, lenOfString) <= 0
         select feature).OrderBy(x => x.ColumnValues);

this is returning the values apple,banana and carrot.I have take ColumnValues fields as the field having the string to compare.As there can be any number of characters in the original string so OrdinalComparison is right approach here.

In this example I have taken the variable lenOfString as "1" but you can define this appropriately depending upon the length of the string.Since here length is "1"( we are comparing "c"), I have set the length as "1".

Upvotes: 3

Related Questions