Tuesday, April 17, 2012

Updating any Object through Linq Query



public class TestClass
{
    public String RollNo { get; set; }
    public String Name { get; set; }
    public String ClassName { get; set; }
}
ObservableCollection<TestClass> aaa = new ObservableCollection<TestClass>();

aaa.Add(new TestClass() {
RollNo = "1602", Name = "Khalid Rafique", ClassName = "A" });

aaa.Add(new TestClass() {
RollNo = "1702", Name = "Jamal Ali Khan", ClassName = "A" });


Method1

var result = aaa.Where(c => c.RollNo == "1702");
foreach (TestClass tc in result)
{
tc.Name = textBox4.Text;
      tc.ClassName = textBox1.Text;
}

Method2

aaa
    .Where(c => c.RollNo == "1702")
    .Update(m =>
                {
                  m.Name = textBox4.Text;
                  m.ClassName = textBox1.Text;
                });


Following is the class having extensible Method of Linq update.

public static class LinqExtensableMethods
{
public static void Update(this IEnumerable source, params Action[] updates)
{
    if (source == null)
      throw new ArgumentNullException("source");

    if (updates == null)
      throw new ArgumentNullException("updates");

       foreach (T item in source)
       {
                foreach (Action update in updates)
                {
                    update(item);
                }
       }
   }
}

Method3

var result =  ocTextClass .Where(c => c.RollNo == "1702").ToList().ForEach(tc => tc.Name=TextBox.Text);

No comments:

Post a Comment