Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

how to query datatable using linq?

Posted on 2011-03-12
6
Medium Priority
?
763 Views
Last Modified: 2013-12-17
hi,

I have datatable, and I wanna query specific customer record from datatable using his id by linq,

so how can I do that using linq?

while I was trying, I got null value selected as return !, here is my code snippet:

 
private Customer GetCustomerInfo(string id)
        {
            Customer cm = null;
            var customers = (from customer in dtCustomers.AsEnumerable()
                         //where customer.Field<string>("id") == id
                         select new { 
                             CustomerId = customer["id"],
                             CustomerEnName = customer["EnName"],
                             CustomerArName = customer["ArName"],
                             CustomerClass = customer["EnClass"],
                             CustomerCellPhone = customer["CellPhone"],
                             Telephone = customer["Telephone"],
                             CustomerEmail = customer["Email"],
                             CustomerIsActive = customer["Active"],
                             CustomerNationalId = customer["NationalId"],
                             CustomerNationalIdType = customer["NationalIdType"]
                         }).Take(1);

            foreach (var c in customers)//I got customers always null even the id is correct
            {
                cm = new Customer(c.CustomerId.ToString(), "LMR-" + Other.changeTo6Digits(c.CustomerId.ToString()), c.CustomerEnName.ToString(), c.CustomerArName.ToString(), "", c.CustomerCellPhone.ToString(), c.Telephone.ToString(), c.CustomerEmail.ToString(), c.CustomerClass.ToString(), c.CustomerIsActive.ToString(), "", c.CustomerNationalId.ToString(), c.CustomerNationalIdType.ToString());
                break;
            }
            return cm;

        }

Open in new window

private Customer GetCustomerInfo(string id)
        {
            Customer cm = null;
            var customers = (from customer in dtCustomers.AsEnumerable()
                         //where customer.Field<string>("id") == id
                         select new { 
                             CustomerId = customer["id"],
                             CustomerEnName = customer["EnName"],
                             CustomerArName = customer["ArName"],
                             CustomerClass = customer["EnClass"],
                             CustomerCellPhone = customer["CellPhone"],
                             Telephone = customer["Telephone"],
                             CustomerEmail = customer["Email"],
                             CustomerIsActive = customer["Active"],
                             CustomerNationalId = customer["NationalId"],
                             CustomerNationalIdType = customer["NationalIdType"]
                         }).Take(1);

            foreach (var c in customers)//I got customers always null even the id is correct
            {
                cm = new Customer(c.CustomerId.ToString(), "LMR-" + Other.changeTo6Digits(c.CustomerId.ToString()), c.CustomerEnName.ToString(), c.CustomerArName.ToString(), "", c.CustomerCellPhone.ToString(), c.Telephone.ToString(), c.CustomerEmail.ToString(), c.CustomerClass.ToString(), c.CustomerIsActive.ToString(), "", c.CustomerNationalId.ToString(), c.CustomerNationalIdType.ToString());
                break;
            }
            return cm;

        }

Open in new window

0
Comment
Question by:njgroup
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 18

Expert Comment

by:Gary Davis
ID: 35115920
Seems like you want to have the DataTable Rows collection as enumerable, not the DataTable itself.

Gary Davis
0
 
LVL 64

Accepted Solution

by:
Fernando Soto earned 2000 total points
ID: 35116191
Hi njgroup;

A couple of things your query returns a Anonymous type and NOT a Customer. We know this because in your select clause you have this, select new {, which does not name the type to create and so an Anonymous type is created. Note in the code snippet I have changed that to this, new DtCustomer {, which states to create the new objects of type DtCustomer, the class I also added to the code snippet. An Anonymous type really has no use outside of the method that created it therfore the reason for creating a concrete type DtCustomer to return to the caller. I also changed the Take(1) to FirstOrDefault(). The Take() method returns, "If count is less than or equal to zero, source is not enumerated and an empty IEnumerable(Of T) is returned.", where the FirstOrDefault returns a null if no result was found, better for error checking.

private DtCustomer GetCustomerInfo(string id)
{
    var customer  = (from customer in dtCustomers.AsEnumerable()
                     where customer.Field<string>("id") == id
                     select new DtCustomer { 
                         CustomerId = customer.Field<int>("id"),
                         CustomerEnName = customer.Field<string>("EnName"),
                         CustomerArName = customer.Field<string>("ArName"),
                         CustomerClass = customer.Field<string>("EnClass"),
                         CustomerCellPhone = customer.Field<string>("CellPhone"),
                         Telephone = customer.Field<string>("Telephone"),
                         CustomerEmail = customer.Field<string>("Email"),
                         CustomerIsActive = customer.Field<string>("Active"),
                         CustomerNationalId = customer.Field<int>("NationalId"),
                         CustomerNationalIdType = customer.Field<string>("NationalIdType")
                     }).FirstOrDefault();

    return customer;
}

public class DtCustomer
{
    public int CustomerId {get; set;}    
    public string CustomerEnName {get; set;}    
    public string CustomerArName {get; set;}    
    public string CustomerClass {get; set;}    
    public string CustomerCellPhone {get; set;}    
    public string Telephone {get; set;}
    public string CustomerEmail {get; set;}
    public string CustomerIsActive {get; set;}
    public int CustomerNationalId {get; set;}
    public string CustomerNationalIdType {get; set;} 
}

Open in new window


Fernando
0
 

Author Comment

by:njgroup
ID: 35119903
thanks very much, but I get an strange error on where statement

Unable to cast object of type 'System.Int32' to type 'System.String'.


even I have it as sting but I dont know really why it give variable as integer!



 
private Customer GetCustomerInfo(string id)
        {
            var customer1 = (from customer in dtCustomers.AsEnumerable()
                            where customer.Field<string>("id") == id // <-- exception generated here
                            select new Customer
                            {
                                id = customer.Field<string>("id"),
                                enName = customer.Field<string>("EnName"),
                                arName = customer.Field<string>("ArName"),
                                type = customer.Field<string>("EnClass"),
                                cellPhone = customer.Field<string>("CellPhone"),
                                tel = customer.Field<string>("Telephone"),
                                email = customer.Field<string>("Email"),
                                isActive = customer.Field<string>("Active"),
                                nationalId = customer.Field<string>("NationalId"),
                                nationalIdType = customer.Field<string>("NationalIdType")
                            }).FirstOrDefault();

            return customer1;
        }

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:njgroup
ID: 35119934
Ok, I solve the problem :D thanks very much
0
 

Author Closing Comment

by:njgroup
ID: 35119936
solution is perfect
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 35121463
Not a problem, glad I was able to help.  ;=)
0

Featured Post

More Than Just A Video Library

Train for your certification. Learn the latest DevOps tools. Grow your skillset to do better work.

At Linux Academy, we release new training modules every week so you'll always be up to date on the latest tech.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question