How to sort linq 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/16
14:03 UTC
Read the original article
Hit count: 533
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
{ Drum, Grand Piano, Guitar, Guitarrón, Harp, Piano} << sorted by name
and if I queried "p" the result should be { Piano, Grand Piano, Harp }
but it shows Harp first because of the source list's sequence
and if I add {Grand Piano} to the list and query "piano"
the result shoud be like { Piano, Grand Piano }
or query "guitar"
it should be { Guitar, Guitarrón }
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.
And the further things to do is I need to search the Name, Category or Origin such as.
If i type "Italy" it should found Piano or something from Italy.
Or if I type "string" it should found Guitar.
Is there any way to do those things, please tell me.
Thanks in advance.
© Stack Overflow or respective owner