Filtering Data in a List according to given Member & manipulating them with C#/ Linq

Scenario : want to filter content stored in a Generic List with given key. lets say we want to add all the values in category A, like with there may be number of categories. with this code segment you can add all the values by using few line of code. actually this demonstrate how powerful linq queries are.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1

/// template/ signature class that demonstrate our data srtucture.
public class TemplateClass
public string type { get; set; }

public int val { get; set; }

class Program
static void Main(string[] args)

// Creating a list type object from TemplateClass
List MyDataList = new List();

// adding TemplateClass object instance to MyDataList
TemplateClass a = new TemplateClass();
a.type = “a”;
a.val = 1;

TemplateClass b = new TemplateClass();
b.type = “a”;
b.val = 2;

TemplateClass c = new TemplateClass();
c.type = “b”;
c.val = 22;

TemplateClass d = new TemplateClass();
d.type = “b”;
d.val = 22;

//starting of the real workarond…

// geting allthe types containg in MyDataList
var itemArray = MyDataList.Select(f => f.type).Distinct();

// itarating with all the types found…
foreach(var ii itemArray)

/// you can manipulate this data as yo want. im just printing them

var result = l.FindAll(x => x.type == ii.ToString());

int cont = 0;
foreach (var item in result)
cont = cont + item.val;




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.