Поскольку свойство является String
, но вы хотите отсортировать его численно, вероятно, лучше всего было бы реализовать IComparable
, а затем введите свой собственный код сортировки в методе CompareTo
. Тогда вам не нужно писать более сложный оператор Lambda каждый раз, когда вы хотите сортировать список, вы можете просто вызвать метод Sort()
в списке.
Вы также можете обрабатывать случаи, когда FileName
свойство не содержит подчеркивание или является null
, а не получать исключения в вашем OrderBy
кода (что случилось бы с большинством других ответов).
Я сделал несколько других изменений также - переопределить метод ToString
, так что вы можете легко отображать значение в окне консоли, и используется автоматический синтаксис свойств для FileName
собственности, поэтому мы можем удалить поле подкладочный:
class xxx : IComparable<xxx>
{
public string FileName { get; set; }
public int CompareTo(xxx other)
{
// Short circuit if any object is null, if the
// Filenames equal each other, or they're empty
if (other == null) return 1;
if (FileName == null) return (other.FileName == null) ? 0 : -1;
if (other.FileName == null) return 1;
if (FileName.Equals(other.FileName)) return 0;
if (string.IsNullOrWhiteSpace(FileName))
return (string.IsNullOrWhiteSpace(other.FileName)) ? 0 : -1;
if (string.IsNullOrWhiteSpace(other.FileName)) return 1;
// Next, try to get the numeric portion of the string to compare
int thisIndex;
int otherIndex;
var thisSuccess = int.TryParse(FileName.Split('_')[0], out thisIndex);
var otherSuccess = int.TryParse(other.FileName.Split('_')[0], out otherIndex);
// If we couldn't get the numeric portion of the string, use int.MaxValue
if (!thisSuccess)
{
// If neither has a numeric portion, just use default string comparison
if (!otherSuccess) return FileName.CompareTo(other.FileName);
thisIndex = int.MaxValue;
}
if (!otherSuccess) otherIndex = int.MaxValue;
// Return the comparison of the numeric portion of the two filenames
return thisIndex.CompareTo(otherIndex);
}
public override string ToString()
{
return FileName;
}
}
Теперь, вы можете просто позвонить Sort
в списке:
List<xxx> list = new List<xxx>
{
new xxx {FileName = "13_a"},
new xxx {FileName = "8_a"},
new xxx {FileName = null},
new xxx {FileName = "1_a"},
new xxx {FileName = "zinvalid"},
new xxx {FileName = "2_a"},
new xxx {FileName = ""},
new xxx {FileName = "invalid"}
};
list.Sort();
Console.WriteLine(string.Join("\n", list));
// Output (note the first two are the empty string and the null value):
//
//
// 1_a
// 2_a
// 8_a
// 13_a
// invalid
// zinvalid
вы хотите сказать, у вас есть список классов, которые вы хотите, чтобы отсортировать их собственности Name? Было бы полезно, если бы вы показали образец кода класса и как вы храните его экземпляры. –
показать свой класс и пример значений –
Вы говорите о номерах «N_» в начале имени вашего файла? –