编辑(将我的旧方法移至底部)
既然您要求我在您的评论中提供帮助,那么这里有一种不同的方法可以满足您的需求:
您的示例数据(前四行是您的最新要求):
var list = new List<String>(){
"CM901K_Spare_parts_EN_rev.04-2",
"CM901K_Spare_parts_EN_rev.04-1",
"CM901K_Spare_parts_EN_rev.04-3",
"CM901K_Spare_parts_EN_rev.04-2",
"rev.04-2",
"CM_Manual_EN_rev.01",
"CM_Manual_EN_rev.02",
"CM_Manual_EN_REV.05",
"CM_Manual_EN_REV.06",
"CM_Manual_EN_REV.07",
"CM12-CM6K_Spare_parts_DK_rev.01",
"CM12-CM6K_Spare_parts_DK_rev.03",
"BT_Dansk_Manual_NOM",
"CM_Svensk_Manual",
"CM901-CM30_Manual_RUS",
"D_Polsk_Manual",
"HPB_spansk_old"
};
首先没有修订,然后另一个按修订排序(每组最高):
var withRev = list.Where(s => s.IndexOf("rev.", StringComparison.OrdinalIgnoreCase) > -1);
var withoutRev = list.Except(withRev);
var orderedWithRev = withRev
.Select(r => {
int RevIndex = r.LastIndexOf("rev.", StringComparison.OrdinalIgnoreCase);
String[] tokens = r
.Substring(RevIndex + "rev.".Length)
.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
return new
{
Item = r,
RevIndex,
RevisionItem = r.Substring(0, RevIndex),
MainRevision = int.Parse(tokens[0]),
SubRevision = tokens.Length > 1 ? int.Parse(tokens[1]) : 0
};
})
.GroupBy(x => x.RevisionItem.ToLower())
.Select(g => g
.OrderByDescending(x => x.MainRevision)
.ThenByDescending( x => x.SubRevision)
.First().Item);
foreach (var wr in withoutRev)
listBox1.Items.Add(wr);
foreach (var r in orderedWithRev)
listBox1.Items.Add(r);
这是演示:http: //ideone.com/fGFZ7
旧答案:
如果字符串始终具有上述格式,最简单的方法是使用Int32.Parse
、String.Substring
和:String.LastIndexof
Enumerable.Max
int highestNum = list.Where(s => s.Contains("."))
.Max(s => int.Parse(s.Substring(s.LastIndexOf(".")+1)));
或获取字符串:
String highestNumString = list.Where(s => s.Contains("."))
.OrderByDescending(s => int.Parse(s.Substring(s.LastIndexOf(".")+1)))
.First();
编辑:这是一个演示:http: //ideone.com/0EeFg