Create DataTable via Linq - linq

Please advice how I can create a datatable with the following source:
public class MyClass : IEquatable<My>
{
public int field1 { get; set; }
public int field2 { get; set; }
}
List<MyClass> lst = new List<MyClass>();
MyClass e = new MyClass;
e.field1 = 1;
e.field2 = 2;
lst.Add(e);
How I can create the datatable for field1 and field2 values using Linq ?

Unfortunately you can't use any cool LINQ specific code but you can create a DataTable, add the Columns, loop over the List you've populated
DataTable dt = new DataTable();
dt.Columns.Add("field1");
dt.Columns.Add("Field2");
lst.ForEach(l => {
var dr = dt.NewRow();
dr[0] = l.field1;
dr[1] = l.field2;
dt.Rows.Add(dr);
});

You can Use CopyToDataTable extension Method. Check MSDN article How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow
DataTable table = lst.CopyToDataTable();

Related

Linq results type?

I would like to replace "var" with the actual type definition. I believe it returns an IEnumerable<>, but I can't figure out what to put for T? I tried debugging with GetType(), but still don't get it...
var LinqResults = from row in dt.AsEnumerable()
orderby row.Field<string>("Category"), row.Field<int>("WorkOrderVersion")
group row by new { Category = row.Field<string>("Category"), WorkOrderVersion = row.Field<int>("WorkOrderVersion") } into grp
select new
{
Category = grp.Key.Category,
WorkOrderVersion = grp.Key.WorkOrderVersion,
};
You can't combine a use of an anonymous type with a specific type because anonymous types provide no name for you to put in for a T inside IEnumerable<T>. In fact, use of anonymous types is an important use case for adding var to the C# language in the first place.
You can define a named type for the result, lie this:
class VersionedWorkOrder {
public string Category { get; set; }
public int WorkOrderVersion { get; set; }
}
IEnumerable<VersionedWorkOrder> linqResults = from row in dt.AsEnumerable()
orderby row.Field<string>("Category"), row.Field<int>("WorkOrderVersion")
group row by new { Category = row.Field<string>("Category"), WorkOrderVersion = row.Field<int>("WorkOrderVersion") } into grp
select new VersionedWorkOrder {
Category = grp.Key.Category,
WorkOrderVersion = grp.Key.WorkOrderVersion
};

The entity or complex type 'AdventureWorks2012Model.Product' cannot be constructed in a LINQ to Entities query

As you can see, I got this error when I built Data Gird using Kendo UI. Does anybody could point out where I'm wrong in my code below.
private IEnumerable<Product> GetSubProduct()
{
var context = new AdvenDBEntities();
var subcate = context.Products.Select(p => new Product
{
ProductID = p.ProductID,
Name = p.Name,
Color = p.Color,
ListPrice = p.ListPrice,
}).ToList();
return subcate;
}
Error:
The entity or complex type 'AdventureWorks2012Model.Product' cannot be constructed in a LINQ to Entities query.
Thank you so much for your time!
Since Product is an entity of model, you are creating new object of this entity while selecting the records, which is NOT good idea, I am NOT sure how model will handle this kind of behaviour that is why it is preventing you to do so, (I guess). Anyway you can change the code to this,
private IEnumerable<Product> GetSubProduct()
{
var context = new AdvenDBEntities();
var subcate = context.Products.ToList();
return subcate;
}
BTW your function name indicating that you are missing a Where clause.
Also you can create some custom DTO class and use it instead.
E.g.
class ProductDTO
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public decimal ListPrice { get; set; }
}
private IEnumerable<ProductDTO> GetSubProduct()
{
var context = new AdvenDBEntities();
var subcate = context.Products.Select(p => new ProductDTO
{
ProductID = p.ProductID,
Name = p.Name,
Color = p.Color,
ListPrice = p.ListPrice,
}).ToList();
return subcate;
}
The first bad smell code I can point out for you. DBContext implements IDisposable so you are responsible for calling Dispose on it. In all, but one case in here, using block
You must build query to get all the product and then extract from it.
private IEnumerable<Product> GetSubProduct()
{
using (var context = new AdvenDBEntities())
{
// Get all constructed type product and then select from it
var subcate = context.Products
.ToList()
.Select(p => new Product
{
ProductID = p.ProductID,
Name = p.Name,
Color = p.Color,
ListPrice = p.ListPrice,
});
return subcate;
}
}

Linq to Entities using joins and generic Lists

I'm using Linq and just started working with it.
My gridview was populating when I was using a single table, but now I am trying to join a Client First Name from the Client Info table.
Error is Event_Setup does not contain a definition for ClientFirstName. So it is checking Event_Setup table instead of Client_Info.
public List<EventData> GetDetails()
{
using (EMSEntities db = new EMSEntities())
{
var context = from events in db.Event_Setup
join clients in db.Client_Info on events.ClientId equals clients.ClientId
select events;
List<EventData> newEvent = new List<EventData>();
foreach (var e in context)
{
EventData test = new EventData();
test.Event_Title = e.EventTitle;
//Error on e.ClientFirstName, Event Setup does not contain Definition
(located in Client_Info table not Event Setup)
test.Name = e.ClientFirstName;
test.Start_Date = e.EventDateFrom;
test.End_Date = e.EventDateFrom;
newEvent.Add(test);
}
return newEvent;
}
}
DAL
public class EventData
{
public string Event_Title { get; set; }
public string Name { get; set; }
public DateTime? Start_Date { get; set; }
public DateTime? End_Date { get; set; }
}
This code is not doing anything with the joined clients data. You can see it is just selecting events:
var context = from events in db.Event_Setup
join clients in db.Client_Info on events.ClientId equals clients.ClientId
select events;
Once you get out of that LINQ statement, clients is gone. It doesn't merge any data for you. You need to do a projection, like this:
var context = from events in db.Event_Setup
join clients in db.Client_Info on events.ClientId equals clients.ClientId
select new EventData
{
Event_Title = events.EventTitle,
Name = clients.ClientFirstName,
Start_Date = events.EventDateFrom,
End_Date = events.EventDateFrom
};
Thank you for that Cory, here's what the list would like for anyone who views this questions
foreach (var e in context)
{
EventData test = new EventData();
test.Event_Title = e.Event_Title;
test.Name = e.Name;
test.Start_Date = e.Start_Date;
test.End_Date = e.End_Date;
newEvent.Add(test);
}
return newEvent;

WP: How to use ToList() method for select multiple columns statement in linq to sql?

I selected 4 columns from my table by using select statement LINQ to SQL. Then I create a new List to store the query result. BUT, the code room.ToList(); is WRONG.
Why cannot we use "rooms_list = room.ToList()"?
How should we do to solve the problem???
Thanks for teaching me!
private void btnTest_Click(object sender, EventArgs e)
{
List<string> rooms_list = new List<string>();
using (LVDatabaseEntities database = new LVDatabaseEntities())
{
var room = from x in database.PHONGCHOIs
select new { x.TENPHONG, x.MATKHAUPHONG, x.CHUPHONG, x.SOLUONG };
rooms_list = room.ToList();
}
MessageBox.Show(rooms_list.Count.ToString());
}
Your rooms_list = room.ToList() is wrong, because it is not the List of type string.
To fix this, first create a class for a room
class Room
{
string TENPHONG { get; set; }
string MATKHAUPHONG { get; set; }
string CHUPHONG{ get; set; }
string SOLUONG{ get; set; }
}
Then, change your code like this
List<Room> rooms_list = new List<Room>();
using (LVDatabaseEntities database = new LVDatabaseEntities())
{
var rooms = from x in database.PHONGCHOIs
select new Room{
TENPHONG = x.TENPHONG,
MATKHAUPHONG = x.MATKHAUPHONG,
CHUPHONG = x.CHUPHONG,
SOLUONG = x.SOLUONG };
rooms_list = room.ToList();
}
MessageBox.Show(rooms_list.Count.ToString());
*Not tested. Let me know if anything didn't work

converting linq result to dictionary<string, int>

I'm quite new to csharp and linq, so am having some trouble with a simple enough casting issue.
I have a simple object -
public class AskQuestionFormView
{
public string QuestionText { get; set; }
public Dictionary<string,int> Location { get; set; }
}
and a linq query
AskQuestionFormView aqfv = new AskQuestionFormView();
var result = from c in db.Countries
.ToDictionary(c => c.LocationName.ToString(),
c=>c.ID)
select c;
aqfv.Location = (Dictionary<string,int>)result;
but I'm getting the following error -
System.InvalidCastException: Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Collections.Generic.KeyValuePair`2[System.String,System.Int32],System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]]' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Int32]'.
What am I doing wrong?
Thanks in advance.
Your query is attempting to query from the dictionary, which is returning a KeyValuePair when you use select c. You just need to generate a Dictionary from the table, so try this instead:
var result = db.Countries.ToDictionary(c => c.LocationName, c => c.ID);
aqfv.Location = result;
Try it like this:
var result = (from c in db.Countries
select c).ToDictionary(c => c.LocationName.ToString(),
c=>c.ID);
aqfv.Location = result;

Resources