在 C# 中有没有办法将链表转换为字符串? [英] In C# is there a way to convert a linked list to a string?

查看:41
本文介绍了在 C# 中有没有办法将链表转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,有没有办法将链表转换为字符串?

In C# is there a way to convert a linked list to a string?

我有一个句子链表和另一个单词链表.我想检查单词链表中单词的句子链表,并认为一个好方法是将单词链表转换为字符串.

I have a linked list of sentences and another linked list of words. I want to check the sentences linked list for the words in the words linked list and was thinking a good approach would be to convert the words linked list to a string.

还考虑使用嵌套的 while 循环.

Also considering using a nested while loop.

推荐答案

认为一个好的方法是将单词链表转换为字符串.

was thinking a good approach would be to convert the words linked list to a string.

任何时候你有一个 X 的列表和一个 Y 的列表,并且你想检查 X 中的任何元素是否在 Y 中,你需要的可能是一个散列集(而不是一个列表)

Any time you have a list of X and a list of Y, and you want to check whether any of the elements in X are in Y, what you need is probably a hash set (not a list)

哈希集提供固定值的快速查找.你的算法应该是:

Hashsets offer fast lookups of fixed values. Your algorithm should be:

  • 将搜索列表加载到集合中
  • 枚举search-in的列表,反复询问当前项是否在集合中
    var hs = listOfWords.ToHashSet();

    foreach(var sentence in listOfSentences){
      foreach(var word in sentence.Split()){
        if(hs.Contains(word))
        {
          ...
        }
      }
    }

或者采用 LINQ 风格的方法

or in a LINQ flavored approach

    var hs = listOfWords.ToHashSet();

    var result = listOfSentences.Where(sentence=> 
       sentence.Split().Any(word => 
           hs.Contains(word)
       )
    );

注意:c# 字符串的散列是默认情况下区分大小写的,并且每个字符都有助于字符串相等.对于 hello"、world"、foo"、bar" 的单词列表和以下句子的列表:Hello world!"、";Foo bar." - 这些句子不包含单词列表中的任何单词.Hello 不等于helloworld! 不等于world.仔细处理你的句子,以便将苹果与苹果进行比较 - 例如去除标点符号,并使大小写相等,例如

Caution: c# hashing of strings is, be default, case sensitive and every character contributes to string equality. For a word list of "hello","world","foo","bar" and a list of sentences of: "Hello world!", "Foo bar." - these sentences do NOT contain any of the words in the word list. Hello is not equal to hello, world! is not equal to world. Carefully process your sentences so you are comparing apples with apples - e.g. strip punctuation, and make case equal, for example

这篇关于在 C# 中有没有办法将链表转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆