LINQ : How to query how to sort result by most similarity/equality

Posted by aNui on Stack Overflow See other posts from Stack Overflow or by aNui
Published on 2010-04-15T22:40:42Z Indexed on 2010/04/15 22:43 UTC
Read the original article Hit count: 264

Filed under:
|
|
|
|

I want to do a search for Music instruments which has its informations Name, Category and Origin as I asked in my post.

But now I want to sort/group the result by similarity/equality to the keyword such as. If I have the list

{ Harp, Piano, Drum, Guitar, Guitarrón }

and if I queried "p" the result should be { Piano, Harp }
but it shows Harp first because of the list's sequence

and if I add {Grand Piano} to the list and query "piano"
the result shoud be like { Piano, Grand Piano }

here's my code

static IEnumerable<MInstrument> InstrumentsSearch(IEnumerable<MInstrument> InstrumentsList, string query, MInstrument.Category[] SelectedCategories, MInstrument.Origin[] SelectedOrigins)
{
    var result = InstrumentsList
        .Where(item => SelectedCategories.Contains(item.category))
        .Where(item => SelectedOrigins.Contains(item.origin))
        .Where(item =>
            {
                if (
                        (" " + item.Name.ToLower()).Contains(" " + query.ToLower())
                        || item.Name.IndexOf(query) != -1
                    )
                {
                    return true;
                }
                return false;
            }
        )
        .Take(30);

    return result.ToList<MInstrument>();
}

Or the result may be like my old self-invented algorithm that I called "by order of occurence",
that is just OK to me.

Is there any way to do that, please tell me.

Thanks in advance.

© Stack Overflow or respective owner

Related posts about c#

Related posts about search