2

输入 1: List<string>,例如:

“你好”、“世界”、“堆栈”、“溢出”。

输入2:(List<Foo>两个属性,字符串a,字符串b),eg:

Foo 1:a:“你好!” b:字符串。空

Foo 2:a:“我喜欢 Stack Overflow” b:“这是有史以来最好的网站!”

所以我想以Dictionary<string,int>. 单词,以及它在 中出现的次数List<Foo>,在a b字段中。

当前的第一遍/我的头代码,这太慢了:

var occurences = new Dictionary<string, int>();
foreach (var word in uniqueWords /* input1 */)
{
    var aOccurances = foos.Count(x => !string.IsNullOrEmpty(x.a) && x.a.Contains(word));
    var bOccurances = foos.Count(x => !string.IsNullOrEmpty(x.b) && x.b.Contains(word));
    occurences.Add(word, aOccurances + bOccurances);
}
4

2 回答 2

1

大致:

  1. 从第一个输入构建字典 ( occurrences),可选择使用不区分大小写的比较器。
  2. 对于Foo第二个输入中的每个,RegEx用于拆分ab成词。
  3. 对于每个单词,检查键是否存在于occurrences. 如果存在,则递增并更新字典中的值。
于 2013-04-23T05:22:18.253 回答
0

您可以尝试连接两个字符串 a + b。然后做一个正则表达式将所有单词提取到一个集合中。然后最后使用按查询分组进行索引。

例如

void Main()
{
    var a = "Hello there!";
    var b =  "It's the best site ever!";

    var ab = a + " " + b;

    var matches = Regex.Matches(ab, "[A-Za-z]+");
    var occurences = from x in matches.OfType<System.Text.RegularExpressions.Match>()
                    let word = x.Value.ToLowerInvariant()
                    group word by word into g
                    select new { Word = g.Key, Count = g.Count() };
    var result = occurences.ToDictionary(x => x.Word, x => x.Count);
    Console.WriteLine(result);
}

建议进行一些更改的示例...编辑。只需重新阅读要求....有点奇怪,但是嘿...

void Main()
{
    var counts = GetCount(new [] {
        "Hello there!",
        "It's the best site ever!"
    });
    Console.WriteLine(counts);
}


public IDictionary<string, int> GetCount(IEnumerable<Foo> inputs)
{
    var allWords =      from input in inputs
                        let matchesA = Regex.Matches(input.A, "[A-Za-z']+").OfType<System.Text.RegularExpressions.Match>()
                        let matchesB = Regex.Matches(input.B, "[A-Za-z']+").OfType<System.Text.RegularExpressions.Match>()
                        from x in matchesA.Concat(matchesB)
                        select x.Value;
    var occurences = allWords.GroupBy(x => x, (x, y) => new{Key = x, Count = y.Count()}, StringComparer.OrdinalIgnoreCase);

    var result = occurences.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase);
    return result;
}
于 2013-04-23T05:22:27.400 回答