Kuldip Rana
Kuldip Rana

Reputation: 131

get DataTable from Linq Query

I want to get a Datatable from Linq Query, Here is what i done..

public static DataTable GetAllDataNoWise(string UniqueNo)
{
    using (var objEntity = new DbContext())
    {
        var Query = from TBL in objEntity.GenerateCodes.AsEnumerable()
                    where TBL.UniqueNo == UniqueNo
                    select new
                    {
                        PrimaryID = TBL.GenerateCodeID,
                        TBL.Code,
                        ExpiryDate = TBL.ExpiryDate.ToShortDateString(),
                    };

        DataTable dt = LINQToDataTable(Query);
        return dt;
    }
}
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
    DataTable dtReturn = new DataTable();

    PropertyInfo[] oProps = null;

    if (varlist == null) return dtReturn;

    foreach (T rec in varlist)
    {
        if (oProps == null)
        {
            oProps = ((Type)rec.GetType()).GetProperties();
            foreach (PropertyInfo pi in oProps)
            {
                Type colType = pi.PropertyType;

                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                == typeof(Nullable<>)))
                {
                    colType = colType.GetGenericArguments()[0];
                }

                dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
            }
        }

        DataRow dr = dtReturn.NewRow();

        foreach (PropertyInfo pi in oProps)
        {
            dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
            (rec, null);
        }

        dtReturn.Rows.Add(dr);
    }
    return dtReturn;
}

Error is generated like

An object reference is required for the non-static field, method, or property Code.LINQToDataTable<<anonymous type: int PrimaryID, string Code, string ExpiryDate>>(IEnumerable<<anonymous type: int PrimaryID, string Code, string ExpiryDate>>)

Upvotes: 0

Views: 369

Answers (1)

Jason W
Jason W

Reputation: 13179

Since the first method is static, it can't call your other method unless it is static or instantiated from an object reference.

You can either add static to your second method

public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)

Or instantiate the class containing your second method and call it from the first method:

var obj = new MyClass();
DataTable dt = obj.LINQToDataTable(Query);

Upvotes: 2

Related Questions