我有一个文本框,用户在其中输入他需要搜索的字符串。如果用户仅输入一个单词字符串,那么我可以从数据库中检索正确的数据,但是如果用户输入一个多单词字符串,则我的代码将失败。
我正在使用EntityFramework来获取数据。
这是我的代码,用于使用单个单词字符串获取数据。
public ActionResult SearchResult(string search)
{
var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(search) || oh.Description.Contains(search));
List<Mobiles> prod = new List<Mobiles>();
foreach (var p in j)
{
Mobiles Mob = new Mobiles();
Mob.Description = p.Description;
Mob.ImgUrl = p.Url;
Mob.MobileName = p.MobileName;
Mob.Price = Convert.ToString(p.Price);
Mob.SlNo = p.SlNo;
prod.Add(Mob);
}
return View("~/Views/Product/Index.cshtml", prod);
}
我尝试使用split将字符串拆分成单个单词,但无法获取正确的数据。
string str = null;
string[] strArr = null;
int count = 0;
str = //UserInput;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
答案 0 :(得分:1)
string str = null;
string[] strArr = null;
int count = 0;
str = search;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
string i = strArr[count];
var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(i) || oh.Description.Contains(i));
//MessageBox.Show(strArr[count]);
foreach (var p in j)
{
Mobiles Mob = new Mobiles();
Mob.Description = p.Description;
Mob.ImgUrl = p.Url;
Mob.MobileName = p.MobileName;
Mob.Price = Convert.ToString(p.Price);
Mob.SlNo = p.SlNo;
prod.Add(Mob);
}
}
在我帮助您解决问题的过程中-这是最终代码
答案 1 :(得分:1)
我写了一个例子来解决您的问题。希望您将从守则中受益。
首先创建移动类:
public class Mobile
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
下一步创建扩展方法以检查是否存在值:
public static bool ContainsAny(this string haystack, params string[] needles)
{
foreach (var needle in needles)
{
if (haystack.Contains(needle))
return true;
}
return false;
}
最后创建主体和测试数据:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StackOverFlow
{
static class Program
{
static void Main()
{
List<Mobile> mobiles = new List<Mobile>
{
new Mobile{Id = 1,Name = "samsung galaxy s3",Description = "model"},
new Mobile{Id = 2,Name = "nokia N67",Description = "nokia n96 time"},
new Mobile{Id = 3,Name = "iphone 5s",Description = "test"},
new Mobile{Id = 4,Name = "samsung galaxy packet",Description = "this time"},
new Mobile{Id = 5,Name = "iphone ipad",Description = "now"},
new Mobile{Id = 6,Name = "glx c5",Description = "time"},
};
string[] search = "galaxy time 5s".Split(' ');
var result = mobiles.Where(c => c.Name.ContainsAny(search) ||
c.Description.ContainsAny(search)).ToList();
foreach (var item in result)
{
Console.WriteLine(item.Id + "-" + item.Name + "-" + item.Description);
}
Console.ReadKey();
}