我知道这比最初提出的问题要多,但它仍然与主题相匹配,我将它包括在内,以供稍后搜索此问题的其他人使用。这不需要在搜索的字符串中匹配整个单词,但是可以使用 Ahmad 帖子中的代码轻松修改它。
//use this method to order objects and keep the existing type
class Program
{
static void Main(string[] args)
{
List<TwoFields> tfList = new List<TwoFields>();
tfList.Add(new TwoFields { one = "foo ASP.NET barfoo bar", two = "bar" });
tfList.Add(new TwoFields { one = "foo bar foo", two = "bar" });
tfList.Add(new TwoFields { one = "", two = "barbarbarbarbar" });
string keyword = "bar";
string pattern = Regex.Escape(keyword);
tfList = tfList.OrderByDescending(t => Regex.Matches(string.Format("{0}{1}", t.one, t.two), pattern).Count).ToList();
foreach (TwoFields tf in tfList)
{
Console.WriteLine(string.Format("{0} : {1}", tf.one, tf.two));
}
Console.Read();
}
}
//a class with two string fields to be searched on
public class TwoFields
{
public string one { get; set; }
public string two { get; set; }
}
.
//same as above, but uses multiple keywords
class Program
{
static void Main(string[] args)
{
List<TwoFields> tfList = new List<TwoFields>();
tfList.Add(new TwoFields { one = "one one, two; three four five", two = "bar" });
tfList.Add(new TwoFields { one = "one one two three", two = "bar" });
tfList.Add(new TwoFields { one = "one two three four five five", two = "bar" });
string keywords = " five one ";
string keywordsClean = Regex.Replace(keywords, @"\s+", " ").Trim(); //replace multiple spaces with one space
string pattern = Regex.Escape(keywordsClean).Replace("\\ ","|"); //escape special chars and replace spaces with "or"
tfList = tfList.OrderByDescending(t => Regex.Matches(string.Format("{0}{1}", t.one, t.two), pattern).Count).ToList();
foreach (TwoFields tf in tfList)
{
Console.WriteLine(string.Format("{0} : {1}", tf.one, tf.two));
}
Console.Read();
}
}
public class TwoFields
{
public string one { get; set; }
public string two { get; set; }
}