如何使用OrderBy<>在我的LINQified正则表达式?

时间:2015-04-07 15:17:48

标签: c# regex linq linq-to-objects

我在这里找到了如何从html文件中提取不同的元素 How can I query a text file for distinct instances of a pattern?

......结果很好。我得到(截断):

<span class="sam" title="This is Sam Clemens speaking">
<span class="others" title="This is 'The Sphynx' speaking">
<span class="others" title="This is the stagecoach driver speaking">
<span class="others" title="This is someone other than the main characters speaking">
<span class="others" title="The station-boss is speaking">
<span class="others" title="This is 'an elderly pilgrim' speaking">
<span class="others2" title="This is Jack speaking">
<span class="bemis" title="This is Bemis speaking">

我想对这些进行排序,所以以上是:

<span class="bemis" title="This is Bemis speaking">
<span class="sam" title="This is Sam Clemens speaking">
<span class="others" title="The station-boss is speaking">
<span class="others" title="This is 'an elderly pilgrim' speaking">
<span class="others" title="This is 'The Sphynx' speaking">
<span class="others" title="This is someone other than the main characters speaking">
<span class="others" title="This is the stagecoach driver speaking">
<span class="others2" title="This is Jack speaking">

这行代码:

distinct_values = MyRegex.Matches(str).Cast<Match>().Select(p => p.Value).Distinct().ToList();

...首先获取数据。我想我需要做这样的事情:

distinct_values = MyRegex.Matches(str).Cast<Match>().Select(p => p.Value).Distinct().OrderBy<>

......但即使我说得对,我也不知道OrderBy的尖括号内应该是什么。

2 个答案:

答案 0 :(得分:3)

尖括号?没什么,这将被推断。这是重要的论点:

.OrderBy(p => p).ToList();

当然,它只能按预期工作,因为整个字符串的排序在这里已经足够了。如果没有,您可能希望同时选择实际字符串和另一个仅具有例如字符串的捕获组。 class值。

答案 1 :(得分:1)

与Select:

相同
 .OrderBy(p => p.PropertyName)

其中PropteryName是您要按其订购的媒体资源的名称。

如果您希望返回值为List,那么:

  .OrderBy(p => p.PropertyName).ToList();

在你的情况下,因为它不是一个对象而是字符串然后:

  .OrderBy(p => p).ToList();