Posts

Showing posts with the label LINQ

Donate

Sorting A HashTable Object Using LINQ In C#.NET And VB.NET

Image
In .NET, you can't directly sort a Hashtable object. A tip on sorting a Hashtable object is to cast it to Dictionary then apply LINQ OrderBy() method to the Hashtable object. See examples below: VB.NET 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Private Sub SortHashTableKey () hash = New Hashtable() hash.Add( "B" , 1 ) hash.Add( "A" , 2 ) hash.Add( "C" , 3 ) Dim dict = hash.Cast( Of DictionaryEntry)() _ .ToDictionary(Function(d) d.Key, Function(d) d.Value) _ .OrderBy(Function(e) e.Key) Console.WriteLine( "Sort by Key" ) For Each item In dict.ToList() Console.WriteLine( String .Format( "{0}, {1}" , item.Key, item.Value)) Next Console.WriteLine(Environment.NewLine) End Sub Private Sub SortHashTableValue ()

Apply LINQ Grouping And Sum Aggregate To A Datatable Object (VB.NET)

Image
Good day! There's a question on vb forums on how to apply LINQ grouping and aggregate function sum to a datatable object. This can be achieved by familiarizing on IGrouping which is a key/value pair interface. Here's how i did it. VB.NET 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Dim dt As New DataTable( "tblEntTable" ) dt.Columns.Add( "ID" , GetType ( String )) dt.Columns.Add( "amount" , GetType ( Decimal )) dt.Rows.Add( New Object () { "1" , 100.51}) dt.Rows.Add( New Object () { "1" , 200.52}) dt.Rows.Add( New Object () { "2" , 500.24}) dt.Rows.Add( New Object () { "2" , 400.31}) dt.Rows.Add( New Object () { "3" , 600.88}) dt.Rows.Add( New Object () { "3" , 700.11}) Dim result = (From orders In dt.AsEnumerable Group orders By ID = orders.Field( Of String )( "ID" ) Into g = Group Select New With { Key ID, .Amount = g.Sum(Function(r) r

ASP.NET MVC 4 Built-in Form Based Authentication

Image
Given that I have some background knowledge of ASP.NET Web Forms Authentication, I decided to try experimenting on MVC 4 authentication/authorization framework. Most of the articles in the internet regarding forms authentication in ASP.NET MVC are custom based approach and less on the built-in technology which is WebData.WebSecurity usage. Not until I found these articles: a. Forms Authentication Customized b. Introduction to forms based authentication in MVC 4 c. Authenticating Users In Asp.net MVC 4 So, to cut the story short, I made an application which utilized the built-in WebMatrix authentication in MVC 4. The first thing to do, is to familiarize those articles to get a good grasp on the topic. The setup of my application are as follows: 1. Web.config      1.1 Added authentication and custom errors <authentication mode= "Forms" > <forms loginUrl= "~/Account/Login" timeout= "2880" /> </authentication>

Populate Select/ListBox items From Html.DropdownList() Selected Value Using jQuery In ASP.NET MVC 4

Image
After familiarizing some basic concepts on ASP.NET MVC 4, I decided to create a simple application which populates a listbox control from a DropDownList helper selected value using jQuery. This simple application included the Entity Framework which targets the AdventureWorks DB.Here's the Model Class: public class CountryRegionsContext : Models.AdventureWorks2008Entities { public DbSet<CountryRegion> Country_Regions { get ; set ; } public DbSet<StateProvince> State_Province { get ; set ; } } Here's the View page: @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Adventure Works Country and State Province Information</h2> <script> $(document).ready( function () { $( "#State" ).prop( "disabled" , true ); $( "#Country" ).change( function () { if ($( "#Country" ).val() != "Select&quo

LINQ Slow Performance In Checking Almost 1 Million Or Large Data (Optimization Problem) In C#

I have a code below which returns an object after satisfying a given condition. 1 2 3 result = listCountryStateCollection.Find(e => (e.CountryName.ToLower().Trim() == accomTempHotel.CityProvinceCountryName[0].CountryName.ToLower().Trim()) && (e.StateName.Trim().ToLower() == accomTempHotel.CityProvinceCountryName[0].StateName.ToLower().Trim()) && (e.SuburbCityName.Trim().ToLower() == accomTempHotel.CityProvinceCountryName[0].SuburbCityName.ToLower().Trim())); The problem I encountered was that, it was slow in getting the desired results. After doing optimization/code checking I came up with a simple solution. The solution is not to include string manipulations in your LINQ but instead the processing should be done using variables as defined below: 1 2 3 4 5 6 string country = accomTempHotel.CityProvinceCountryName[0].CountryName.ToLower().Trim(); string state = accomTempHotel.CityProvinceCountryName[0].StateName.ToLower().Trim(); string s

IOrderedQueryable<T> Extension Method (C#)

Here's a modified version of Nick Harrison's IOrderedQueryable extension method in his dynamic linq query post: static class IQueryableExtensions { public static IOrderedQueryable<TSource> GenericEvaluateOrderBy<TSource>( this IQueryable<TSource> query, string propertyName) { var type = typeof (TSource); var property = type.GetProperty(propertyName); var parameter = Expression.Parameter(type, "p" ); var propertyReference = Expression.Property(parameter, property); //p.ProductName var sortExpression = Expression.Call( typeof (Queryable), "OrderBy" , new Type[] { type, property.PropertyType }, query.Expression, Expression.Quote(Expression.Lambda(Expression.MakeMemberAccess(parameter, property), parameter))); return query.Provider.CreateQuery<TSource>(sortExpression) as IOrderedQueryable<TSource&g

NBuilder Simple Example In C#

Nbuilder is a great tool in developing mock builders to generate data out of you application. Assuming, you don't use database for retrieving records, you can use NBuilder with LINQ capabilities to generate test data. Assuming if you have a class in your model like this: namespace MvcApplication1.Models { public class Product { public int Id { get ; set ; } public string Name { get ; set ; } public double Price { get ; set ; } public string Description { get ; set ; } } } To generate a product object using NBuilder, you may use something like this: Product product = Builder<Product> .CreateNew() .With(x => x.ProductId = productId) .And(x => x.Price = Convert.ToDouble(productId)) .And(x => x.Name = "Mushroom Can" ) .And(x => x.Description = @"Imported from New Zealand. Fresh and Juicy." ) .Build(); Cheers!

How To Sort Dictionary<TKey,TValue> Object By Value Or By Key Using LINQ In C#

Here's a code I got from StackOverflow on how to sort dictionary object by value or by key using LINQ in C#. var sortedDict = ( from entry in SortedWebsiteNames orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value); var sortedDict = ( from entry in SortedWebsiteNames orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);

Invalid Expanded Name In LINQ to XML

Assuming I am reading this xml file using XLINQ. I encountered an error that says invalid expanded name. As i go through this xml file, i found a node images that contains element tags. The parent node is also an element tag. Since i don't use the images tag, I simply remove it using string manipulations. Below is the xml file and the solution: <element> <id> 2768687195 </id> <title> Customer Service Representative </title> <body> Do you dream of being your own boss and choosing the work you do, when you work and who you work for? </body> <url> http://jobs.myjob.careercenter-servicecrew.html </url> <category> <id> job/customer_service </id> <name> Customer Service &amp; Call Center Jobs </name> </category> <source> <id> www </id>

How To Read Or Parse XML Using LINQ And XLinq In C#

Hello, Here's an example on how to read or parse XML file using LINQ and XLINQ in C#. XML Content: <item> <title> Labor Warehouse Associates - Boston, Massachusetts </title> <link> http//www.BostonRecruiter.com/job_display.php?alpha=17343491 </link> <description> Hudson Group is the #1 airport retailer operating in over 400 retail locations in most major airports, throughout the US and Canada. While we are comprised of many </description> <guid> http//www.BostonRecruiter.com/job_display.php?alpha=17343491 </guid> <joblocation> <jobcity> Boston </jobcity> <jobstate> Massachusetts </jobstate> <jobcountry> United States </jobcountry> </joblocation> </item> C# Code: string url = "your xml or rss link" ; string xmlsource = client.DownloadString(url);

Manipulate Object Property Using Lambda Expression In LINQ

Here's how to manipulate or update an object property using Lambda format in LINQ. In this example, I assigned a value to the textbox control's Text property using a delegate that applies the concept of Lambda expressions in LINQ. ShowEmployeeDelegate d = () => { tMessage.Text = "Nelson" ; }; d.Invoke();

How To Call SQL Server Stored Procedure Using LINQ And C#.NET

Good evening. Here's a basic example of how to call a SQL Server Stored Procedure Using LINQ And C#.NET 1. Make sure you have Northwind database in your Sql server. 2. Create a simple stored procedure to retrieve customers based on a specific country. The parameter of the stored procedure is of type varchar. 3. Create a simple asp.net website or winforms or console project. 4. Add a Linq to SQL class to your project. 5. Make sure to add the stored procedure in your linq to sql class. 6. In your asp.net website, add a button,textbox and a gridview. 7. In your button event click, add the following snippet: 1 2 3 4 5 6 7 8 protected void Bind () { string country = this .txtCity.Text.Trim(); var cr = new NorthWindDataContext(); var north = cr.CustomerByCountry(country); this .gridCustomers.DataSource = north; this .gridCustomers.DataBind(); } That's it...

Donate