使用LINQ从列表中动态列 [英] Dynamic Columns from List using LINQ

查看:59
本文介绍了使用LINQ从列表中动态列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要帮助,才能使用LINQ从列表中获取列.像这样

Hi,

I need help to get the columns from list dyanmic using LINQ. Like this,

List<DashBoard> dashboardlist = (List<DashBoard>)objList;

objList = (from obj in dashboardlist select new { obj.EprotexStatus, obj.RecReference, obj.RecDescription, obj.RecDate, obj.ModifiedDate, obj.RectypeDesc }).ToList();


上面的方法可以很好地使用LINQ从列表中返回列.

但是我想在以下过程中从列表中选择特定的列


above is working fine to return columns from list using LINQ.

But I want specific columns from list in following process

List<DashBoard> dashboardlist = (List<DashBoard>)objList;
string strColumns = "RecDate,ModifiedDate";
objList = (from obj in dashboardlist select new { strColumns }).ToList();



上面的陈述我想只基于字符串column变量获得两列.

在此先感谢



Above statment i want get two columns only based on string columns variable.

Thanks in advance

推荐答案

您可以确定执行此操作,但需要额外的精力.

使用动态Linq库 [
You can definately do it but it needs some extra efforts.

Use Dynamic Linq Library[^]

Thanks.


大家好,

我得到了使用不同方法的解决方案.像这样

我将列表转换为DataSet,然后遵循方法
Hi All,

I got solution for using different method. Like this,

I converted the list to DataSet and then following method
DataView view = new DataView();
DataTable dtTable=view.ToTable(false,<string array="">);
</string>



我的要求很好,

谢谢大家.



It is working fine my requirement

Thank you for all.


您需要使用C#4.0中提供的动态"功能,因为在编译时不知道属性列表.一个名为"Projection"(参见下文)的小辅助方法可以帮助从源对象获取单个属性.


这是一个简单的示例:
You need to use the "dynamic" feature available in C# 4.0, because the list of properties is not known at compile time. A small helper method called ''Projection'' (see below) could help to get individual properties from source objects.


Here is a quick example:
public void Test() {
    var data = new[] {
        new TestData { X = 1, Y = 2, Z = 3 }
    ,   new TestData { X = 2, Y = 4, Z = 6 }
    };
    var strColumns = "X,Z".Split(',');
    foreach (var item in data.Select(a => Projection(a, strColumns))) {
        Console.WriteLine("{0} {1}", item.X, item.Z);
    }
}
private static dynamic Projection(object a, IEnumerable<string> props) {
    if (a == null) {
        return null;
    }
    IDictionary<string,object> res = new ExpandoObject();
    var type = a.GetType();
    foreach (var pair in props.Select(n => new {
        Name = n
    ,   Property = type.GetProperty(n)})) {
        res[pair.Name] = pair.Property.GetValue(a, new object[0]);
    }
    return res;
}
class TestData {
    public int X { get; set; }
    public int Y { get; set; }
    public int Z { get; set; }
}


这篇关于使用LINQ从列表中动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆