Saturday, May 12, 2012

Working with LINQ


Working with LINQ (1)


Write the following code inside button in windows form .

string[] names = { "Burke", "Connor", "Frank",
                       "Everett", "Albert", "George",
                       "Harris", "David" };

    IEnumerable<string> query = from s in names
                               where s.Length == 5
                               orderby s
                               select s.ToUpper();

    foreach (string item in query)
      MessageBox.Show(item);

Working with LINQ (2)


Step 1 : Create database
create database HRDB

Step 2 : creating the following table
create table People (
    Name nvarchar(32) primary key not null,
    Age int not null,
    CanCode bit not null
)

Step 3 : Add the following data into People table

Step 4 : Add the following two lines above class form .

using System.Data.Linq;
using System.Data.Linq.Mapping;

Step 5 : Write the following block of code into project 
[Table(Name = "People")]
    public class Person
    {
        [Column(DbType = "nvarchar(32) not null")]
        public string Name;

        [Column]
        public int Age;

        [Column]
        public bool CanCode;
    }

Step 6 : Design  form .



Step 7 : inside Show Data button, write the following code .

DataContext context = new DataContext(
     "Data Source=.;Initial Catalog=HRDB;Integrated Security=True");

            Table<Person> custs = context.GetTable<Person>();

            var query = from c in custs
                      
                      
                        select new
                        {
                            c.Name,
                           
                            c.Age
                        };

            foreach (var item in query)
            {
                listBox1.Items.Add(item.Name + "-" + item.Age);
            }



No comments:

Post a Comment