0

Please consider this lists:

var List1 = {};
var List2 = {"A"};
var List3 = {"AE"};
var List4 = {"A", "B", "F", "H", "AA", "AC", "AE"};

This lists are Excel Columns. Now I want to find column name that come before a given column name, for example if I want to find that which column come before "N" I want to get this results from lists:

null // From List 1
"A"  // From List 2
null // From List 3
"H"  // From List 4

How I can write a LINQ query that returns this result for me?

Thanks

Arian
  • 12,793
  • 66
  • 176
  • 300

1 Answers1

1

Assuming that the list is ordered, this is one possible way :

YourList.TakeWhile(o => ExcelToNumber(o) < ExcelToNumber("N"))
        .LastOrDefault();

ExcelToNumber() is a method to convert excel column name to integer, as mentioned in this post. I included the method definition below for easy reference, credit 100% to contributors of the linked post :

int ExcelToNumber(string x) {
    return x.Aggregate(0, (s, c) => s * 26 + c - 'A' + 1);
}
Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137