Posts

Showing posts with the label LINQ

Donate

How To Remove Duplicate Items In A List<T> Using IEqualityComparer<T>

Image
Good evening. Here's a simple demo on how to remove duplicate items in a List object using IEqualityComparer given that the generic list's type is complex. First we setup a simple model Employee class with Age, Name and Address properties. class Employee { public int Age { get ; set ; } public string Name { get ; set ; } public string Address { get ; set ; } } Next is to create a comparer class that implements IEqualityComparer interface. class EmployeeComparer : IEqualityComparer<Employee> { public bool Equals(Employee emp1, Employee emp2) { if (Object.ReferenceEquals(emp1, emp2)) return true ; if (Object.ReferenceEquals(emp1, null ) || Object.ReferenceEquals(emp2, null )) return false ; return (emp1.Age == emp2.Age) && (emp1.Name == emp2.Name) && (emp1.Address == emp2.Address); } public int GetHashCode(Employee obj) {

Match Item That Exists In A List Using Regular Expression And LINQ

Hi! Using Any() in LINQ, we can match/find an item that exists in a List<T> or IEnumerable using Regular Expressions. if (Products.Any(t => Regex.IsMatch(t, ProductsFromFrance.FrenchProdPattern)) { //true statement here.. } Where Products is the List object and ProductsFromFrance.FrenchProdPattern is the Regular Expression pattern.

Navigation Properties In Entity Framework Using Database First Approach

Image
Good day! Here's a simple step by step tutorial on exploring the Navigation Properties of EF using the DB approach. According to MSDN , Navigation properties provide a way to navigate an association between two entity types. Every object can have a navigation property for every relationship in which it participates. Navigation properties allow you to navigate and manage relationships in both directions, returning either a reference object (if the multiplicity is either one or zero-or-one) or a collection (if the multiplicity is many). You may also choose to have one-way navigation, in which case you define the navigation property on only one of the types that participates in the relationship and not on both. Given the description, this example demonstrates the concept using two tables Employees and Dependents wherein you search for a particular employee and you can access the related dependents of that employee. To start with, just perform the steps given below. Step 1. Cre

Pivot DataTable Using LINQ In C# And VB.NET

Hello, A question was brought up in the forums on how to Pivot a DataTable object here. The OP has already a solution with reference to this link Cross Tab / Pivot from Data Table . An alternative solution is to utilize the features of LINQ using group by statement to achieve the desired output. This solution consists of few lines of code compared with the solution from the forum post. C# Code var query = ( from students in dt.AsEnumerable() group students by students.Field< string >( "StudID" ) into g select new { StudID = g.Key, Eng = g.Where(c => c.Field< string >( "SubSht" ) == "Eng" ).Sum(c => c.Field< double >( "Score" )), Fre = g.Where(c => c.Field< string >( "SubSht" ) == "Fre" ).Sum(c => c.Field< double >( "Score" )), Mat = g.Where(c => c.Field< string >( "SubSht" ) == "Mat" ).Sum(c => c.Field< double &

Update DataTable Values Using LINQ In C# And VB.NET

Image
Hello, Here's how to update DataTable value(s) using Method or Query syntax in LINQ. C# Code private void Form1_Load( object sender, EventArgs e) { DataTable dt = new DataTable( "tblEntTable" ); dt.Columns.Add( "ID" , typeof ( string )); dt.Columns.Add( "Amount" , typeof ( decimal )); dt.Rows.Add( new object [] { "1" , 100.51}); dt.Rows.Add( new object [] { "2" , 200.52}); dt.Rows.Add( new object [] { "3" , 500.24}); dt.Rows.Add( new object [] { "4" , 400.31}); dt.Rows.Add( new object [] { "5" , 600.88}); dt.Rows.Add( new object [] { "6" , 700.11}); //QuerySyntax(dt); MethodSyntax(dt); } private void QuerySyntax(DataTable dt) { var result = from row in dt.AsEnumerable() select new { ID = row.Field< string >( "ID" ), Amount = 900.23 }; DataGridView1.DataSource = result.ToList(); } private void MethodSyntax(DataTa

Login To Facebook Account Using C#, Webbrowser And LINQ

Hi, Here's how to login to your facebook account using Webbrowser control and LINQ in Windows Forms. The input elements are checked through their attributes like "email" for email fields, "password" for password fields and "submit" for submission control. These codes are inside the DocumentCompleted event. C# code WebBrowser1.Document.GetElementsByTagName( "input" ).Cast<HtmlElement>().FirstOrDefault(t => t.GetAttribute( "type" ) == "email" ).SetAttribute( "value" , "your email address" ); WebBrowser1.Document.GetElementsByTagName( "input" ).Cast<HtmlElement>().FirstOrDefault(t => t.GetAttribute( "type" ) == "password" ).SetAttribute( "value" , "your user name" ); WebBrowser1.Document.GetElementsByTagName( "input" ).Cast<HtmlElement>().FirstOrDefault(t => t.GetAttribute( "type" ) == "submit" ).I

Find Elements In XML From List Collection Using LINQ And C#

Hello, Given you have a List object with a number of string elements and you want to check whether the elements in the list are found in the XML file, options are your going to use the for each loop or the List.ForEach() action to traverse the List and perform searching through the XML file. XML File <?xml version="1.0" encoding="utf-8" ?> <catalog> <book id= "bk101" > <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description> An in-depth look at creating applications with XML. </description> </book> <book id= "bk102" > <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price>

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

Given the XML file below which is a sample popularized my Microsoft, here's how to traverse with that XML file using LINQ to XML XDocument class. XML File <?xml version="1.0" encoding="utf-8" ?> <catalog> <book id= "bk101" > <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description> An in-depth look at creating applications with XML. </description> </book> <book id= "bk102" > <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description> A former architect battles corporate zombies, an ev

LINQ to Entities does not recognize the method 'System.String ToString()

When working with Dropdownlists in ASP.NET MVC, I encountered an error as stated in the title of this post when casting an int variable through LINQ Select() statement. List<SelectListItem> itemCountries = new List<SelectListItem>(); itemCountries.AddRange(( from country in _context.CascadeCountries select country) .Select(x => new SelectListItem { Value = x.CountryID.ToString(), //error here... Text = x.CountryName }).ToList()); After doing some research, I found out that the statement returned by the Select statement above is IQueryable and the itemCountries variable is an IEnumerable . So, the fix for this issue is to cast the LINQ statement with AsEnumerable() and then followed by the Select() statement which sets the values for the SelectListItems properties. List<SelectListItem> itemCountries = new List<SelectListItem>(); itemCountries.AddRange(( from country in _context.Casca

Attach Single Event To A Control Array At Run Time Using LINQ And C#

In a scenario wherein you need to attach a single event like CheckedChanged() to a control array such as CheckBox controls, the common way to do it is using for each or for loop. Another way to achieve it is using LINQ's ForEach() method as demonstrated below. Event Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 void CheckBoxGeneric_CheckedChanged ( object sender, EventArgs e) { var checkBox = (CheckBox)sender; if (checkBox.Name == "chkBurger" ) { //... } else if (checkBox.Name == "chkSoda" ) { //... } else { //... } } Attach the event to the control array 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 private CheckBox[] OrderItems; OrderItems = new CheckBox[] { chkBurger, chkSoda, chkIceCream }; private void Form1_Load ( object sender, EventArgs e) { //solution 1 using foreach loop //foreach (var checkControl in OrderItems) //{ // checkControl.CheckedChanged += new EventHandler(CheckBoxGeneric_CheckedChanged);

Show All Folders Inside Directory Sorted By Creation Time Using Linq In C# And VB.NET

Here's a solution using LINQ that will retrieve all folders inside a specific directory in order of creation time. C# 1 2 3 4 5 6 7 8 9 10 11 12 string path = @"C:\" ; if (Directory.Exists(path)) { DirectoryInfo dir = new DirectoryInfo(path); DirectoryInfo[] directories = dir.GetDirectories(). OrderByDescending(p => p.CreationTime). ToArray(); if (directories.Length > 0) { foreach (DirectoryInfo directory in directories) { ListBox1.Items.Add(directory.Name); } } } VB.NET 1 2 3 4 5 6 7 8 9 10 11 12 Dim path As String = "C:\" If Directory.Exists(path) Then Dim dir As New DirectoryInfo(path) Dim directories As DirectoryInfo() = dir.GetDirectories(). OrderByDescending(Function(p) p.CreationTime). ToArray()

How To Convert DataTable To List Using LINQ And C#

Hello, The code below converts a DataTable object to generic List object using LINQ and C#. It assumes that the DataTable columns match with class properties. C# Code 1 2 3 4 5 6 7 8 var personEnumerable = table.AsEnumerable(); List<Person> ListPosition = new List<Person>(); ListPosition = ( from item in personEnumerable select new Person { ID = item.Field< int >( "ID" ).ToString(), Salary = item.Field< double >( "Salary" ).ToString() }).ToList(); Class 1 2 3 4 5 public class Person { public string ID { get ; set ; } public string Salary { get ; set ; } }

Get Latest Order For Each Customer Using C# And LINQ To SQL

Given the task that my client requires me to retrieve all customers and their recent orders made for their report, the solution for this using LINQ is to join two tables namely Customers and Orders . Then the script retrieves the latest order code in the subquery with the condition that it should match with the customer id in the outer query. The subquery also applies arranging the orders made according to recent date and then select the latest using FirstOrDefault() which is the equivalent to Top 1. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 var results = ( from order in _context.Orders join cus in _context.Customers on order.CustomerID equals cus.CustomerID where (order.OrderID == ( from subOrder in _context.Orders where subOrder.CustomerID == order.CustomerID orderby subOrder.OrderDate descending select subOrder.OrderID).FirstOrDefault())

Apply LINQ Grouping And Sum Aggregate To A Datatable Object (C#)

Image
Good day! Here's the C# version of this post. Apply LINQ Grouping and Sum aggregate to a Datatable Object (VB.NET) Code: 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 36 DataTable dt = new DataTable( "tblEntTable" ); dt.Columns.Add( "ID" , typeof ( string )); dt.Columns.Add( "amount" , typeof ( 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 }); var results = ( from orders in dt.AsEnumerable() group orders by orders.Field< string >( "ID" ) into g select new { ID = g.Key,

Return Top Three Largest Values In A VB.NET Array Using LINQ

Sample snippet on getting the three largest values in an array using LINQ. VB.NET 1 2 3 4 5 6 7 8 9 10 11 12 13 Dim rand As New Random() Dim numbers As New List( Of Int32) For index = 1 To 20 Step 1 ' add a list item which is a number from 1 through 100 numbers.Add(rand.Next(1, 100)) Next Dim topThreeLargest = numbers.OrderByDescending(Function(t) t).Take(3) Console.WriteLine( "Top three largest elements in the array: " ) For Each item As String In topThreeLargest Console.WriteLine(item) Next

LINQ To SQL In Operator With Subquery

Given the following sql statement below using In operator with subquery as it's argument, I need to convert this to LINQ statement. SELECT [CountryRegionCode] ,[Name] ,[ModifiedDate] FROM [AdventureWorks2012].[Person].[CountryRegion] where CountryRegionCode in ( select distinct [CountryRegionCode] from [AdventureWorks2012].[Person].StateProvince) After doing some readings on LINQ documentation, I found it's equivalent LINQ code using let . model.CountryRegionsList = ( from country in _context.CountryRegions let subQuery = ( from stateprovince in _context.StateProvinces select stateprovince.CountryRegionCode). Distinct () where subQuery. Contains (country.CountryRegionCode) select country).ToList();

Entity Framework Join Two Tables If The Foreign Key Is A Nullable Column

Image
Hello, When retrieving records by joining two tables wherein the foreign key of the referenced table is a nullable column, and you want to return all records from the primary table, with or without the matching rows in the right table, the query would be using left join rather than inner join. So in LINQ expression, rather than inner join, revise the query to left join as presented below. Show products with matching categories, disregarding other products without categories MVC View: Code: 1 2 3 4 5 6 7 8 9 10 11 model.Products .AddRange( ( from item in context.Products .Where(item => item.Name.Trim().StartsWith(selectedLetter)) join category in context.ProductSubcategories on item.ProductSubcategoryID equals category.ProductSubcategoryID select new ProductModel() { ProductName = item.Name, ProductID = item.ProductID, ProductNumber = item.ProductNumber, Color = ( string .IsNullOrEmpty(item.Color)) ? "NA" : item.Color, St

Find Checked Treenode In TreeView Control Using LINQ In VB.NET

Here's one way of searching through a treenode using LINQ. Assuming that the search criteria is a List or array object. 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 Public Class Form1 Public Shared mat As List( Of String ) = Nothing Private Sub Form1_Load (sender As System.Object, e As System.EventArgs) Handles MyBase .Load mat = New List( Of String ) mat.Add( "Books" ) mat.Add( "VB" ) mat.Add( "Drinks" ) mat.Add( "Food" ) mat.Add( "Tea" ) mat.Add( "Chod" ) End Sub Private Sub Button1_Click (sender As System.Object, e As System.EventArgs) Handles Button1.Click If Not (mat Is Nothing ) Then For Each tn As String In mat If (tvMat.Nodes.Find(tn, True ).FirstOrDefault() IsNot Nothing ) Then If (tvMat.Nodes

The type of one of the expression in the join clause is incorrect.Type inference failed in the call to GroupJoin In C#

Hi, I just tested on grouping two collections using GroupJoin approach in LINQ to XML. In the example, the two collections are Customers and Companies. In which, companies served as grouping for the customers. In simple terms, identify a customer of which company he or she belongs. The code below produced an error The type of one of the expression in the join clause is incorrect.Type inference failed in the call to GroupJoin. XElement companiesAndCustomers = new XElement( "CompaniesAndCustomers" , from company in companies join customer in customers on company equals customer.CompanyName into groupCompany select new XElement( "Company" , new XAttribute( "CompanyName" , company.CompanyName), new XAttribute( "Country" , company.Country), from subCustomer in groupCompany select new XElement( "Customer" , subCustomer.LastN

List Running Computer Processes By Array Names Using LINQ In C# And VB.NET

Image
Here's a snippet on how to retrieve running process in your computer by array names using LINQ. C# Code 1 2 3 4 5 6 7 8 List<Process> procs = new List<Process>(); procs = new List< string >() { "firefox" , "iexplore" , "ssms" , "notepad++" , "chrome" } .SelectMany(o => Process.GetProcessesByName(o)).ToList(); foreach ( var item in procs) { Console.WriteLine(item.ProcessName); } VB.NET 1 2 3 4 5 6 Dim procs As IEnumerable( Of Process) = _ { "firefox" , "iexplore" , "ssms" , "notepad++" , "chrome" }.SelectMany(Function(proc) Process.GetProcessesByName(proc)) For Each p In procs Console.WriteLine(p.ProcessName) Next Console.ReadLine() Output

Donate