1

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.

Also considering using a nested while loop.

Arthur
  • 11
  • 2
  • 2
    Probably not the right approach. You probably need something like `sentences.Where(s => words.Any(s.Contains))` – Charlieface Nov 24 '21 at 09:26
  • Maybe compile the words list to an reg expression and iterate over the sentence list to find matched pattern. – TinglePan Nov 24 '21 at 09:28
  • 1
    Can you share what you tried so far? – Prasad Telkikar Nov 24 '21 at 09:42
  • 1
    The [built-in `LinkedList` class](https://learn.microsoft.com/en-gb/dotnet/api/system.collections.generic.linkedlist-1) implements `IEnumerable`; the `string.Join` method has an overload which accepts `IEnumerable`. Why can't you just pass your list to `string.Join`? – Richard Deeming Nov 24 '21 at 10:05
  • Also, LinkedList is rarely the best datastructure to use. A regular List is better in the vast majority of cases. [This question explains why](https://stackoverflow.com/questions/34170566/bjarne-stroustrup-says-we-must-avoid-linked-lists), it is for c++, but the same is true for c#. – JonasH Nov 24 '21 at 10:06

1 Answers1

0

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

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:

  • load the list of searching-for into the set
  • enumerate the list of searching-in, repeatedly asking if the current item is in the set
    var hs = listOfWords.ToHashSet();

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

or in a LINQ flavored approach

    var hs = listOfWords.ToHashSet();

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

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

Caius Jard
  • 72,509
  • 5
  • 49
  • 80