none
linq expression for string comparison that counts equal words RRS feed

  • Question

  • Hello there,


    I want to define a linq expression that finds all list items they matches my needle best. For example I have the following list and needle: 


    List<string> colors = new List<string>();
    colors.Add("yello dark blue orange");
    colors.Add("red apple green");
    string needle = "blue orange apple"
    

    Now I want to get all list items back where the needle fits best. That means  "blue orange apple" and "yellow dark blue orange" have 2 words in common and  "blue orange apple" and "red apple green" only one, so it should return a list that contains the element "yellow dark blue orange".


    • Edited by Zero3000 Friday, February 15, 2019 9:52 AM
    Friday, February 15, 2019 9:51 AM

Answers

  • Check this:

    List<string> result =
        colors
            .Select( s => new { s, n = s.Split( ).Intersect( needle.Split( ) ).Count( ) } )
            .Where( s => s.n != 0 )
            .OrderByDescending( p => p.n )
            .Take( 1 )
            .Select( p => p.s )
            .ToList( );





    Friday, February 15, 2019 1:14 PM

All replies

  • Check this:

    List<string> result =
        colors
            .Select( s => new { s, n = s.Split( ).Intersect( needle.Split( ) ).Count( ) } )
            .Where( s => s.n != 0 )
            .OrderByDescending( p => p.n )
            .Take( 1 )
            .Select( p => p.s )
            .ToList( );





    Friday, February 15, 2019 1:14 PM
  • Hi Zero3000

    Thank you for posting here.

    For your question, you want to define a LINQ expression that it could find all list items when they match your needle best.

    You could try the following code to get it.

    var result1 = from m in colors
                              group m by new
                              {
                                  m,
                                  n = m.Split().Intersect(needle.Split()).Count()
                              } into g
                              where (g.Key.n != 0)
                              orderby g.Key.n descending
                              select g.Key.m;
                List<string> list = result1.Take(1).ToList();

    Hope my solution could be helpful.

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.



    Monday, February 18, 2019 6:15 AM
    Moderator