Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

c# - How can I make this LINQ search method handle more than two terms?

The following search method works fine for up to two terms.

How can I make it dynamic so that it is able to handle any number of search terms?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestContains82343
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> tasks = new List<string>();
            tasks.Add("Add contract to Customer.");
            tasks.Add("New contract for customer.");
            tasks.Add("Create new contract.");
            tasks.Add("Go through the old contracts.");
            tasks.Add("Attach files to customers.");

            var filteredTasks = SearchListWithSearchPhrase(tasks, "contract customer");

            filteredTasks.ForEach(t => Console.WriteLine(t));
            Console.ReadLine();
        }

        public static List<string> SearchListWithSearchPhrase(List<string> tasks, string searchPhrase)
        {
            string[] parts = searchPhrase.Split(new char[] { ' ' });
            List<string> searchTerms = new List<string>();
            foreach (string part in parts)
            {
                searchTerms.Add(part.Trim());
            }

            switch (searchTerms.Count())
            {
                case 1:
                    return (from t in tasks
                            where t.ToUpper().Contains(searchTerms[0].ToUpper()) 
                            select t).ToList();
                case 2:
                    return (from t in tasks
                            where t.ToUpper().Contains(searchTerms[0].ToUpper()) && t.ToUpper().Contains(searchTerms[1].ToUpper())
                            select t).ToList();
                default:
                    return null;
            }

        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about replacing

switch (searchTerms.Count())
{
    case 1:
        return (from t in tasks
                where t.ToUpper().Contains(searchTerms[0].ToUpper())
                select t).ToList();
    case 2:
        return (from t in tasks
                where t.ToUpper().Contains(searchTerms[0].ToUpper()) && t.ToUpper().Contains(searchTerms[1].ToUpper())
                select t).ToList();
    default:
        return null;
}

By

(from t in tasks
 where searchTerms.All(term => t.ToUpper().Contains(term.ToUpper()))
 select t).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...