【发布时间】:2014-06-19 11:16:57
【问题描述】:
这是给你的一个假设。如果您有一个字符串列表,是否可以按该字符串中存在的给定字符对该列表进行排名?
考虑这个伪代码:
List<String> bunchOfStrings = new List<String>;
bunchOfStrings.Add("This should not be at the top");
bunchOfStrings.Add("This should not be at the top either");
bunchOfStrings.Add("This should also not be at the top");
bunchOfStrings.Add("This *SHOULD be at the top");
bunchOfStrings.Add("This should not be at the top");
bunchOfStrings.Add("This should be *somewhere close to the top");
buncOfStrings.OrderBy(x => x.Contains("*"));
在上面的代码中,我想对列表进行重新排序,以便每当星号 (*) 出现在字符串中时,它都会将该字符串放在列表的顶部。
如果这甚至可以使用 LINQ 或类似方法,有什么想法吗?
【问题讨论】:
-
好吧,您可以使用
OrderBy并提供一个自定义的IComparer<string>实现来进行比较。
标签: c# linq lambda custom-lists