Пример #1
0
        /// <summary>
        /// Sort a list of objects by relevance to a given string using Levenshtein Distance
        /// </summary>
        /// <typeparam name="T">Any object type</typeparam>
        /// <param name="objects">The list of objects to sort</param>
        /// <param name="searchTerm">The term to measure relevance to</param>
        /// <param name="propertyToSortBy">x => x.PropertyName [the term will be matched against the value of this property]</param>
        public static IEnumerable <T> SortByRelevance <T>(this IEnumerable <T> objects, string searchTerm, Func <T, string> propertyToSortBy)
        {
            var lev = new Levenshtein(searchTerm);

            return(objects.Select(o => new
            {
                score = lev.DistanceFrom(propertyToSortBy(o)),
                obj = o
            })
                   .OrderBy(x => x.score)
                   .Select(x => x.obj));
        }
Пример #2
0
        /// <summary>
        /// Sort a list of objects by relevance to a given string using Levenshtein Distance
        /// </summary>
        /// <typeparam name="T">Any object type</typeparam>
        /// <param name="objects">The list of objects to sort</param>
        /// <param name="searchTerm">The term to measure relevance to</param>
        /// <param name="propertyToSortBy">x => x.PropertyName [the term will be matched against the value of this property]</param>
        /// <param name="maxDistance">The maximum levenstein distance to qualify an item for inclusion in the returned list</param>
        public static IEnumerable <T> SortByRelevance <T>(this IEnumerable <T> objects, string searchTerm, Func <T, string> propertyToSortBy, int?maxDistance = null)
        {
            var lev = new Levenshtein(searchTerm);

            var res = objects.Select(o => new
            {
                score = lev.DistanceFrom(propertyToSortBy(o)),
                obj   = o
            });

            if (maxDistance.HasValue)
            {
                res = res.Where(x => x.score <= maxDistance.Value);
            }

            return(res.OrderBy(x => x.score)
                   .Select(x => x.obj));
        }