从单个文本框中搜索单个和多个关键字

时间:2016-11-24 14:57:32

标签: c# asp.net linq

var db = new MatriModel();
string s = txtKeyWord.Text;
string[] words = s.Split(',');
int count = words.Length;

if (count <= 5)
{
    SerachByKeyWordPanel.Visible = true;
    var KeyWord = db.tblProfiles.Where(x => words.Contains(x.tblCaste.Caste) && words.Contains(x.tblCountry.Country) && words.Contains(x.City) && words.Contains(x.tblOccupation.Occupation) && words.Contains(x.tblMotherTongue.MotherTongue)).Select(x => new
  {
        ProfileID = x.ProfileID,
        ProfileFor = x.tblProfileFor.ProfileFor,
  }.ToList();

通过上面的代码,我可以获得多个关键字的详细信息,但同时,我也希望通过单个关键字获取记录。

请有人帮助我,先谢谢

1 个答案:

答案 0 :(得分:0)

请参阅以下基于简化对象的代码段:

class MatrixModel {
    public string ProfileId {get; set;}
    public string Caste {get; set;}
    public string Country {get; set;}
    public string City {get; set;}
    public string Occupation {get; set;}
    public string MotherTongue {get; set;}
}

public static void Main()
{
    var db = new MatrixModel[]{
        new MatrixModel {
            ProfileId = "1",
            Caste = "Caste1",
            Country = "USA",
            City = "Miami",
            Occupation = "System administrator",
            MotherTongue = "English"
        },
        new MatrixModel {
            ProfileId = "2",
            Caste = "Caste1",
            Country = "India",
            City = "Mumbai",
            Occupation = "developer",
            MotherTongue = "English"
        },      
        new MatrixModel {
            ProfileId = "3",
            Caste = "Caste1",
            Country = "England",
            City = "London",
            Occupation = "developer",
            MotherTongue = "English"
        },              
    };
    string s = "Caste1, England";
    string[] words = s.Split(',');
    int count = words.Length;

    if (count <= 5)
    {
                IEnumerable<MatrixModel> KeyWord = db;
                foreach(var par in words) 
                {
                    var parTrimmed = par.Trim();
                    KeyWord = KeyWord
                        .Where(x => x.Caste == parTrimmed
                            || x.Country == parTrimmed
                            || x.City == parTrimmed
                            || x.Occupation == parTrimmed 
                            || x.MotherTongue == parTrimmed);
                }

                var result = KeyWord.Select(x => new
                    {
                        ProfileID = x.ProfileId,
                    }).ToList();

                foreach(var item in result){
                    Console.WriteLine(item);
                }
        }
}

结果如下:

{ ProfileID = 3 }