简体   繁体   中英

Resultant LinQ Query to compare

In .NET 3.5, ASP.NET using C#

From the below Query,

var query = table.AsEnumerable()
             .Where(p => p.Field<string>("Customer_Code") == "1001")
             .Select(p => new 
                           {
                              Location = p.Field<string>("Location"),
                              Country = p.Field<string>("Country")
                           })
              .Distinct();

I want to compare the resultant query results such as Location, Country with each DataRow of a DataTable Location and Country

OR In Reverse way, I want to compare each Query result with each DataTable Row

How can i perform the same?

Sample Datatable:

Location     Country
Bangalore    India
Hyderabad    India
Florida       USA
London        UK
Delhi        India

Try this

create a class

Class Temp
{
    public String Location {get;set;}
    public String Country {get;set;}
}

then

List<Temp> list = table.AsEnumerable()
             .Where(p => p.Field<string>("Customer_Code") == "1001")
             .Select(p => new Temp()
                           {
                              Location = p.Field<string>("Location"),
                              Country = p.Field<string>("Country")
                           })
             .Distinct().ToList();

then compare like this

foreach (Temp t in list)
{
    foreach(DataRow row in table.Rows)
    {
       //do your comparison
    }
}

How about you do the following to check for a match:

foreach(DataRow row in table.Rows)
{
   var result = query.SingleOrDefault(x=> 
            x.Location.ToLower() = row["Location"].ToLower() 
            && x.Country.ToLower() = row["Country"].ToLower()
        );
   if(result != null)
   {
        //Hurray, result is a match!
   }
}

Note: *A .Where(...).Count >0 check might be better dependant on what you will find in the query. If you expect multiple hits, use .Where() instead of .SingleOrDefault()

New idea If you don't mind processing your DataTable and storing it in an IEnumerable, you could use LINQ-joins to connect the two lists. A bit harder but I think it will be more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM