Exclude Similarities in List of Strings to extract the Difference

前端 未结 2 1360
無奈伤痛
無奈伤痛 2021-01-26 11:14

I have a list of sentences that are the same except for the Title of the book.

How can I loop through the list and exclude the similarities to find the title of the book

2条回答
  •  渐次进展
    2021-01-26 11:59

    A working solution using LINQ:

    List sentences = new List() { };
    List titles = new List() { };
    
    sentences.Add("The book named Lord of the Flies is a classic.");
    sentences.Add("The book named To Kill a Mockingbird is a classic.");
    sentences.Add("The book named The Catcher in the Rye is a classic.");
    sentences.Add("Hello");
    sentences.Add("The book named ");
    
    
    titles = sentences.Where(sentence => sentence.Length > "The book named ".Length + " is a classic".Length)
                .GroupBy(sentence => sentence.Substring(0, 15), sentence => sentence.Remove(sentence.Length - " is a classic".Length).Substring("The book named ".Length))
                .Where(g => g.Key == "The book named ")
                .SelectMany(g => g)
                .ToList();
    
    foreach (var title in titles)
        WriteLine(title);
    

    First, it filters out sentences too short to meet the criteria, then groups the results by first 15 letters and extracts the titles with String.Remove.

提交回复
热议问题