Sow*_*mya 10 .net c# linq list predicatebuilder
您好我想使用谓词表达式基于搜索字符串创建列表.
我有一个类型产品列表包含不同的名称.
List<products> list1 = new List<products>();
list1.Add(new products("sowmya"));
list1.Add(new products("Jane"));
list1.Add(new products("John"));
list1.Add(new products("kumar"));
list1.Add(new products("ramya"));
listBox1.ItemsSource = list1;
Run Code Online (Sandbox Code Playgroud)
现在我想根据用户输入过滤内容.用户将输入n个字符串,并带有'+'作为分隔符.收到字符串后,我会将它们传递给谓词对象
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
List<products> list2 = new List<products>();
Expression<Func<products, bool>> predicate = PredicateBuilder.True<products>();
if (e.Key == Key.Enter)
{
string Searchstring = textBox1.Text.ToString().Trim();
string[] separator = new string[] { "+" };
string[] SearchItems=Searchstring.Split(separator,StringSplitOptions.None);
foreach (string str in SearchItems)
{
string temp = str;
predicate =p => p.Name.Contains(temp.ToLower());
}
list2 = list1.AsQueryable().Where(predicate).ToList();
listBox1.ItemsSource = list2;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我输入多个字符串(sowmya + jane + john),它只给出最后一个字符串(john)结果,但我想要一个所有匹配字符串的列表
请回答这个问题,因为我正在尝试这个,但我无法得到结果.
请帮忙谢谢.
Era*_*nga 17
将谓词初始化为false
Expression<Func<products, bool>> predicate = PredicateBuilder.False<products>();
Run Code Online (Sandbox Code Playgroud)
您需要使用组合谓词 Or
foreach (string str in SearchItems)
{
string temp = str;
predicate = predicate.Or(p => p.NameToLower().Contains(temp.ToLower()));
}
Run Code Online (Sandbox Code Playgroud)
代码,以防链接进行
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T> () { return f => true; }
public static Expression<Func<T, bool>> False<T> () { return f => false; }
public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13390 次 |
| 最近记录: |