how to write linq to objects query
Using LINQ to Objects, we can query in-memory objects. These objects must have been implemented using IEnumerable
interface. Using LINQ to Objects we can query objects without having to write complex for each loops to retrieve data from a collection. These queries are declarative and hence easier to write. They are more readable and concise. They include powerful filtering, ordering capabilities similar to SQL. The advantage is that we need not write many for loop codes to work with collections objects.
Example of LINQ to Object query
class Customer
{ private string strCode;
private string strName;
public string Code
{
get { return strCode; }
set { strCode=value; }
}
public string Name
{
get { return strName; }
set { strName = value; }
}
static void Main(string[] args)
{
List myCustomers = new List();
Customer cust1 = new Customer();
cust1.Code = "Code1";
cust1.Name = "Cutsomer1";
Customer cust2 = new Customer();
cust2.Code = "Code2";
cust2.Name = "Cutsomer2";
myCustomers.Add(cust1);
myCustomers.Add(cust2);
var q = from c in myCustomers
select c;
foreach (var val in q)
{
Console.WriteLine("{0} {1}", val.Code ,val.Name);
}
Console.ReadLine();
}
Other uses of LINQ to Objects
Strings
We can use LINQ to Objects to transform strings. It can also be used to query data in text files. When we encounter large text in text files, we can split the text and then query. We can also split the text as paragraphs, words and then perform the query.
Reflections
Using reflections, we can retrieve metadata about methods.
File Directories
Using File Directories feature, we can find names of all files which have a specific extension. For example, .com,.exe etc. We can also sort and group list of files and folders. We can also retrieve the size of files in a specific folder. We can compare contents of two folders. We can identify files having the same name but are stored in multiple places.