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

x
?
Solved

Which is better please? Use LINQ directly, Or use it with List class passing a class of my products table?

Posted on 2015-01-08
9
Medium Priority
?
144 Views
Last Modified: 2016-02-15
Hi
I had seen two videos about Linq to sql. Those two  videos has two approaches to bind data to GridView.
      Linq to sql approache:
o       where I select my data into var, then bind it to myGridview. See code below.
Linq-aspx-cs.JPG      List collection class approache:
o      Where I create a class " myProductObject".
o      I initiate an instance List of my class:
List<myProductObject> myList = new List<myProductObject>();
o      Then I fill in myList with my data using Linq.

myProductObject-cs.JPGLINQ-List--aspx-cs.JPG      Please tell me the deference between those two approaches? And which is better?
0
Comment
Question by:Mohammad Alsolaiman
[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
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 400 total points
ID: 40538125
It depends on what you need to do.  Both of those snippets essentially do the same thing, the only difference being that the first example creates an anonymous type rather than the concrete class used in the second example.

If you need to be able to manually create, and manipulate, the custom objects from the database then you want the second approach.  If you are simply loading from a database and binding once, then the approach from the first example will suffice.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40538134
Functionally, there is no difference. I prefer the first approach because it's easier to read.
0
 

Author Comment

by:Mohammad Alsolaiman
ID: 40538261
Thanks to all of you for the reply "If you need to be able to manually create, and manipulate, the custom objects from the database then you want the second approach."
I like it, it sounds good to me.
Do you mean that I can do my manipulating using the properties and the functions inside the class?
If so, would you please guide me to good example of these  manipulations.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 400 total points
ID: 40538278
I should clarify my statement as I did not look closely enough at the code. I prefer the ToList call in the first example over the AddRange call in the second.
0
 
LVL 34

Accepted Solution

by:
it_saige earned 1200 total points
ID: 40538288
The first method uses a well defined type (the class), whereas the second uses an anonymous type.

What does this mean for you.  Well it really depends on how you want to interact with your object.  When using the first method, you can do a direct cast to the databounditem since it is well defined.  With the second, you have to get the cell values directly.  Consider the following:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EE_Q28592993
{
	public partial class Form1 : Form
	{
		private List<DataObject> data = null;
		private bool isLoading = false;

		public Form1()
		{
			InitializeComponent();
			if (data == null)
				data = new List<DataObject>();

			isLoading = true;
			dataGridView1.RowHeadersVisible = false;
			dataGridView2.RowHeadersVisible = false;
			dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
			dataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
			dataGridView1.RowEnter += OnRowEnter;
			dataGridView2.RowEnter += OnRowEnter;
		}

		private void OnLoad(object sender, EventArgs e)
		{
			for (int i = 0; i < 20; i++)
				data.Add(new DataObject() { ID = i, Name = string.Format("SomeName{0}", i), Created = DateTime.Now.AddDays(i) });

			dataGridView1.DataSource = (from row in data select row).ToList();
			dataGridView2.DataSource = (from row in data select new { row.ID, row.Name, row.Created }).ToList();
			isLoading = false;
		}

		private void OnRowEnter(object sender, DataGridViewCellEventArgs e)
		{
			if (!isLoading)
			{
				if (sender is DataGridView)
				{
					DataGridView dgv = sender as DataGridView;
					if (dgv == dataGridView1)
					{
						DataObject row = dgv.Rows[e.RowIndex].DataBoundItem as DataObject;
						MessageBox.Show(string.Format("ID: {0}; Name: {1}; Created: {2}", row.ID, row.Name, row.Created));
					}

					if (dgv == dataGridView2)
					{
						var rowObject = dgv.Rows[e.RowIndex].DataBoundItem;
						object[] row = new object[3];
						row[0] = dgv.Rows[e.RowIndex].Cells[0].Value;
						row[1] = dgv.Rows[e.RowIndex].Cells[1].Value;
						row[2] = dgv.Rows[e.RowIndex].Cells[2].Value;
						MessageBox.Show(string.Format("ID: {0}; Name: {1}; Created: {2}", row[0], row[1], row[2]));
					}
				}
			}
		}
	}

	class DataObject
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public DateTime Created { get; set; }
	}
}

Open in new window

Produces the following output -Capture.JPGIf we place a breakpoint on the OnRowEnter event and select an item from the first datagrid:Capture.JPGWe see that the DataBoundItem *is* a DataObject class object.

However, selecting an item from the second datagrid:Capture.JPG We see that the DataBoundItem does contain the properties of a DataObject class object, but we cannot access them unless we cast it as a DataObject (which when you deal with anonymous types, you do not normally created a class definition for the anonymous contents).Capture.JPG
Now, that being said, there is a way to access the values of the anonymous type by their well defined names without doing a direct cast.  We could use reflection, or (if we are using .NET 4.0) we can use the dynamic type:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EE_Q28592993
{
	public partial class Form1 : Form
	{
		private List<DataObject> data = null;
		private bool isLoading = false;

		public Form1()
		{
			InitializeComponent();
			if (data == null)
				data = new List<DataObject>();

			isLoading = true;
			dataGridView1.RowHeadersVisible = false;
			dataGridView2.RowHeadersVisible = false;
			dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
			dataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
			dataGridView1.RowEnter += OnRowEnter;
			dataGridView2.RowEnter += OnRowEnter;
		}

		private void OnLoad(object sender, EventArgs e)
		{
			for (int i = 0; i < 20; i++)
				data.Add(new DataObject() { ID = i, Name = string.Format("SomeName{0}", i), Created = DateTime.Now.AddDays(i) });

			dataGridView1.DataSource = (from row in data select row).ToList();
			dataGridView2.DataSource = (from row in data select new { row.ID, row.Name, row.Created }).ToList();
		}

		private void OnRowEnter(object sender, DataGridViewCellEventArgs e)
		{
			if (!isLoading)
			{
				if (sender is DataGridView)
				{
					DataGridView dgv = sender as DataGridView;
					if (dgv == dataGridView1)
					{
						DataObject row = dgv.Rows[e.RowIndex].DataBoundItem as DataObject;
						MessageBox.Show(string.Format("ID: {0}; Name: {1}; Created: {2}", row.ID, row.Name, row.Created));
					}

					if (dgv == dataGridView2)
					{
						dynamic rowObject = dgv.Rows[e.RowIndex].DataBoundItem;
						MessageBox.Show(string.Format("ID: {0}; Name: {1}; Created: {2}", rowObject.ID, rowObject.Name, rowObject.Created));
					}
				}
			}
		}

		private void OnShown(object sender, EventArgs e)
		{
			isLoading = false;
		}
	}

	class DataObject
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public DateTime Created { get; set; }
	}
}

Open in new window

Breakpoint the OnRowEnter and viola:Capture.JPGCapture.JPG
So the long and the short of it is this, for easier dataobject access, you would use the well-defined method.  The other method takes more work to get the values out of the object.  In Linq-to-Sql (normally), you are dealing with a well-defined method any way as your datacontext should contain classes that represent the datamodel.

-saige-
0
 

Author Comment

by:Mohammad Alsolaiman
ID: 40538295
kaufmed thanks for the clarification.
Do you mean that both of them are same(returns List collection class). But the first one is easer code!
0
 

Author Comment

by:Mohammad Alsolaiman
ID: 40538314
it_saige thanks for the example you've wrote.
I'll try to understand it (I never write windows form application before) I'll do my best to understand your example.
0
 
LVL 34

Expert Comment

by:it_saige
ID: 40538331
No problem.  It is a lot to digest, especially when asking a question that contains as many code variations as you have.  Dealing with your code variations (as Kaufmed pointed out with regards to AddRange() vs. ToList()); remember that the datasource of the datagrid (for all intents and purposes) *is* a collection and normally collections (by the broadest terms) *are* lists.  The ultimate question then becomes, how do I want to work with the databound object?

-saige-
0
 

Author Closing Comment

by:Mohammad Alsolaiman
ID: 40551171
thanks to all of you for the good Clarification
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

670 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