I know this is more than the original question asked, but it still matches the subject and I'm including it for others who search on this question later. This does not require that the whole word be matched in the strings that are searched, however it can be easily modified to do so with code from Ahmad's post.
//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; }
}