【问题标题】:How to use LinQ query to map the columns in an array?如何使用 LinQ 查询映射数组中的列?
【发布时间】:2015-03-22 03:58:51
【问题描述】:

我想通过映射数组中的列名来将 LinQ 查询写入数据库。

我在数组中有以下列名称

string[] myColumns = {"CustID","FirstName","LastName","OrderID" };

客户模型具有以下属性

public class Customer
{
    public int CustID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我无法使用 LinQ 将列映射到 Customer 表。我尝试按照以下代码实现代码,但没有得到结果。

var myResult=db.Customers.Select(x=>
new
{
myColumns[0]=x.CustID,
myColumns[1]=x.FirstName, 
myColumns[2]=x.LastNmae
}).ToList();

感谢您的帮助

【问题讨论】:

  • 这里您只是替换值,而不是映射它们。如果要映射,请使用字典;如果要分配值,请使用类

标签: c# linq asp.net-mvc-4 linq-to-entities entity-framework-5


【解决方案1】:

基于这个讨论How to add dynamic member name and value to an instance of ExpandoObject class?我找到了我的问题的解决方案,使用下面的方法应该给你动态成员的值

public static List<ExpandoObject> MapColumnsAndGetResult<T>(List<T> YourDataInList, string[] ColumnNames)
    {
        var result = new List<ExpandoObject>();
        foreach (var objClass in YourDataInList)
        {
            if (objClass != null)
            {
                var dynamicClass = new ExpandoObject() as IDictionary<string,object>;
                foreach (var prop in objClass.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
                {
                    if (ColumnNames.Contains(prop.Name))
                    {
                        dynamicClass.Add(prop.Name, prop.GetValue(objClass, null));
                        result.Add((ExpandoObject)dynamicClass);
                    }
                }
            }
        }
        result = result.Distinct().ToList();
        return result;
    }

如何使用:

var dataModel = db.ChapterRepository.GetAll().ToList();
var myResult = MapColumnsAndGetResult(dataModel, myColumns);
foreach (var x in myResult)
        {
            foreach (var property in (IDictionary<String, Object>)x)
            {
                Console.WriteLine(property.Key + ": " + property.Value);
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-03
    • 2013-12-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多