Archive for the ‘LINQ’ Category

My previous post if you had seen,I talked about writing  eventlogs using Log4Net.You can always use the Windows Event Viewer to see the logs.But in case you cannot directly login to machine,you may want to read the logs from code.Here I am sharing a codesnippet on how you you can read using LINQ and bind to a gridview control.

            eventlog.MachineName = whichmachine;
           //this reads the name from a dropdown say for eg Application logs you selected
            eventlog.Log = ddleventlogs.Items[ddleventlogs.SelectedIndex].Value.ToString();
            //queries logs under Application from a selected source         
            var query = from EventLogEntry eventlogentry in eventlog.Entries
                        where eventlogentry.Source == ddleventsource.Text
                        select new
                            Time = eventlogentry.TimeGenerated,
                            Source = eventlogentry.Source,
                            Message = eventlogentry.Message

            eventviewgrid.DataSource = query.ToList();

Is that not simple?LINQ rocks always 🙂

Did you know that LINQ simplifies working with XML data & you need not use Xpath or XQuery for reading XML?Below code queries the xml & populates the listbox with values of Subject node under Book.

<?xml version=”1.0″ encoding=”utf-8″ ?>
      Social Science

     General Science

var books = from nodes in System.Xml.Linq.XElement.Load("Books.xml").Elements("Book")
select nodes;
if (books != null)
foreach (var b in books)


LINQ to query DataTable

Posted: January 13, 2011 in LINQ

I am pretty new to LINQ & today my team mate was suggesting me to learn LINQ & write about it.Just starting with a small homework,how to query datatable using LINQ 🙂

What this snippet does is,there is a DataTable having columns Name,Age,Address etc,LINQ queries the table with name as input & returns Age & Address

string searchname="Anupama";
DataTable dtContacts = new DataTable();
dtContacts = this.GetContactDetails;

var query = from r in this.dtContacts.AsEnumerable()
where r.Field("Name") == searchname
select new{ Age=r["Age"],Address=r["Address"]};

Simple right?Keep Watching this space,I will get back with complicated one’s 🙂