Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

LINQ: Convert String array to List of objects of custom class

Suppose we have a user class
public class User
{
 public string Name { get; set; }
}
and we have the usernames in a string array as shown below
string[] names = new string[5] {"John", "David", "Robert", "Paul", "Mary" };
if we want to convert it as list of User class objects, the general method for this is
List usersList =new List();
foreach(var name in names)
{
usersList.Add(new User(){
Name=name;
});
}
Using LINQ, we can achive the same with a single line
List usersList = names.Select(x => new User() { Name = x } ).ToList();
Happy Coding 😊 !!

Update DataTable row without using Loop statements

Sometime we need to update a single row in a DataTable based on certain criteria. In those situations, we generally use a loop statement to find that record in the DataTable and updates the columns in that row.
LINQ Provides an easy way for this type of cases.We can get the row in the DataTable which matches the criteria by using simple LINQ Query. The changes made in the returned DataRow will effect the DataTable values.
Example: I have the following DataTable

ID          Name       Country
----      ----------   --------
1           Ram           India
2           Martin        USA
3           Raj             India
4           Prem          Australia

Now I  want to Update the 'Country' value to "USA" if ID=3, then it can be done in the following ways

//using Loop
for (int i = 0; i < oDt.Rows.Count; i++)
  {
      if (oDt.Rows[i]["ID"].ToString() == "3")
      {
         oDt.Rows[i]["Country"] = "USA";
         break;
       }
   }


//Without using Loop --using LINQ
DataRow oDr = oDt.AsEnumerable().Where(r => ((string)r["ID"]).Equals("3") ).First();
oDr["Country"] = "USA";

Calling SQL Server inbuilt functions in LINQ

Microsoft introduces a new class 'SqlFunctions', in .NET framework 4, to call the SQL Server inbuilt functions directly in LINQ Queries. It is available in "System.Data.Objects.SqlClient" namespace.

The SqlFunctions class contains methods that expose SQL Server functions to use in LINQ to Entities queries. When you use SqlFunctions methods in LINQ to Entities queries, the corresponding database functions are executed in the database.

Ex: The following example executes a LINQ to Entities query that uses the CharIndex method to return all contacts whose last name starts with "Si"

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
      // SqlFunctions.CharIndex is executed in the database.
     var contacts = from c in AWEntities.Contacts
                           where SqlFunctions.CharIndex("Si", c.LastName) == 1
                           select c;
     foreach (var contact in contacts)
     {
          Console.WriteLine(contact.LastName);
      }
}

Database functions that perform a calculation on a set of values and return a single value (also known as aggregate database functions) can be directly invoked. Other canonical functions can only be called as part of a LINQ to Entities query. To call an aggregate function directly, you must pass an ObjectQuery to the function.

Ex: Below example calls the aggregate ChecksumAggregate method directly. Note that an ObjectQuery is passed to the function, which allows it to be called without being part of a LINQ to Entities query.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
 {
      // SqlFunctions.ChecksumAggregate is executed in the database.
      decimal? checkSum = SqlFunctions.ChecksumAggregate(
            from o in AWEntities.SalesOrderHeaders
           select o.SalesOrderID);
      Console.WriteLine(checkSum);
 }

Note: To Call the Canonical Functions you need to used the EntityFunctions class.

Ex: The following example executes a LINQ to Entities query that uses the DiffDays method to return all products for which the difference between SellEndDate and SellStartDate is less than 365 days:

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
 {
    var products = from p in AWEntities.Products
                 where EntityFunctions.DiffDays(p.SellEndDate, p.SellStartDate) < 365
                  select p;
    foreach (var product in products)
    {
        Console.WriteLine(product.ProductID);
    }
}

For more information about SqlFunctions class, please check the below MSDN links