动态列表的位置
我正在尝试为各种类创建动态filter。 我们只会在运行时知道我们正在处理什么类型。 我需要ColumnName是实际列(不是字符串值)。
有没有一种简单的方法将字符串转换为列?
public static List Filter (this List Source, string ColumnName, string TypeOfCompare, string CompValue) { IQueryable matches = Source.AsQueryable(); if (ColumnName.Length > 0) { matches = (IEnumerable)matches.Where(a => ColumnName == CompValue) } List ReturnList2 = new List(); ReturnList2 = matches.ToList(); return ReturnList2; }
基本上你需要构建一个表达式树。 幸运的是,使用Expression.Property
并不是非常困难。 您可以将其传递给Queryable.Where
,也可以将其编译并传递给Enumerable.Where
。 (显然你也需要使用像Expression.Equal
这样的东西,这取决于你想要做的比较类型。)
CompValue
是实际值吗? 什么是TypeOfCompare
意味着什么?
我不确定LINQ to Entities在哪里适合这个,或者……你只是真正使用LINQ to Objects,据我所见。
编辑:好的,这是一个样本。 它假设你想要平等,但如果是这样,它会做你想要的。 我不知道每次编译表达式树会对性能产生什么影响 – 您可能希望为任何给定的名称/值组合缓存委托:
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; static class Extensions { public static List Filter (this List source, string columnName, string compValue) { ParameterExpression parameter = Expression.Parameter(typeof(T), "x"); Expression property = Expression.Property(parameter, columnName); Expression constant = Expression.Constant(compValue); Expression equality = Expression.Equal(property, constant); Expression> predicate = Expression.Lambda>(equality, parameter); Func compiled = predicate.Compile(); return source.Where(compiled).ToList(); } } class Test { static void Main() { var people = new[] { new { FirstName = "John", LastName = "Smith" }, new { FirstName = "John", LastName = "Noakes" }, new { FirstName = "Linda", LastName = "Smith" }, new { FirstName = "Richard", LastName = "Smith" }, new { FirstName = "Richard", LastName = "Littlejohn" }, }.ToList(); foreach (var person in people.Filter("LastName", "Smith")) { Console.WriteLine(person); } } }
你不能通过一个字符串ColumnName
来传递该列的选择器(我意识到这并不总是可行,但以防它是……)? 这可以用,然后。
顺便说一句,代码太复杂了。 这应该工作:
public static List Filter ( this List Source, Func selector, string CompValue) { return Source.Where(a => selector(a) == CompValue).ToList(); }
然后,您可以按如下方式调用代码:
var result = myList.Filter(x => x.ColumnName, "foo");
你在寻找这样的东西: http : //naspinski.net/post/Writing-Dynamic-Linq-Queries-in-Linq-to-Entities.aspx否则你必须分别处理每个案例,如下所示:
上述就是C#学习教程:动态列表的位置分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
if (columnName == "blah") matches = matches.Where(i => i.Blah == Value); if (columnName == "name") matches = matches.Where(i => i.Name == Value);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1004874.html