In this example, I will show how to query an ArrayList using Linq. Since ArrayList are non-generic IEnumerable collections, the type of variable in the collection must be explicitly declared in the linq query.
I already have a web application setup, so, I will just add a class called Person. This is a very simple class containing only 2 properties – FirstName and LastName. The code for the class is below.
Person Class
- namespace WebApplication1.CSClass
- {
- public class Person
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public override string ToString()
- {
- return FirstName + " " + LastName;
- }
- }
- }
I will then add a web form where I will add an ArrayList, add Person objects to the collection and then query the collection using Linq. The code for this is below.
Query ArrayList with LINQ
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Collections;
- using WebApplication1.CSClass;
- namespace WebApplication1
- {
- public partial class LinqText : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- GetList();
- }
- private void GetList()
- {
- ArrayList list = new ArrayList();
- list.Add(new Person { FirstName = "Scooby", LastName="Doo" });
- list.Add(new Person { FirstName = "Bugs", LastName = "Bunny" });
- list.Add(new Person { FirstName = "Peter", LastName = "Pan" });
- var q = from Person p in list
- orderby p .FirstName
- orderby p.LastName
- select p;
- string br = "<br/>";
- foreach (Person p in q)
- {
- L1.Text += p.ToString() + br;
- }
- }
- }
- }
Note that, in the linq query, the object type is specified. The query will not work unless it is specified.
0 comments:
Post a Comment