0

I would like to write LinQ query to the database by mapping the column names which are in an array.

I have the following column names in the array

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

Customer model has the following properties

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

I am unable to map the columns to the Customer table using LinQ. I tried to implement the code as below code but I did not get the result.

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

I appreciate you help

sridharnetha
  • 2,104
  • 8
  • 35
  • 69
  • Here you are just replacing the values, not mapping them. Use dictionary if you are going to map or class if you are going to assign the values – Sajeetharan Mar 22 '15 at 04:15

1 Answers1

0

Based on this discussion How to add dynamic member name and value to an instance of ExpandoObject class? I have found solutions to my question, Using below method should give you the dynamic members with their values

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;
    }

How to Use:

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);
            }
        }
Community
  • 1
  • 1
sridharnetha
  • 2,104
  • 8
  • 35
  • 69