Showing posts with label c# linq. Show all posts
Showing posts with label c# linq. Show all posts

Thursday, January 2, 2014

question on delegate predicates

in the following class:

class testLinq
    {
       
        public  bool www(string s)
        { return s.Equals("def"); }

        public delegate bool d(string s);

        public void write()
        {
           
            List<String> l = new List<string>() { "abc", "def" };
             
            normal way of doing predicate:  
            Console.WriteLine(l.Find(p => { return p.Equals("def"); }));
            
            bizzare method: 
            Predicate<string> pred = new Predicate<string>(www); 
            Console.WriteLine(l.Find(pred));

            non working method - 
            d di = null;
            di  = www;
            Console.WriteLine(l.Find(di)));
         Why?



            
            Console.ReadLine();


        }


    }

words that c# compiler add to LINQ

for example:
in this case
SortedList<int, string> sl = new SortedList<int, string>() { { 4, "beatrice" }, { 2, "herby" } };

this 
Console.WriteLine(sl.FirstOrDefault((KeyValuePair<int, string> p) => {return p.Key == 4; }).Value);

is equivelant to this:

Console.WriteLine(sl.FirstOrDefault(p => p.Key == 4).Value);

Thursday, March 1, 2012

var in c#

why does c# have a var keyword ?
if you answer because of linq- that would be partly correct
consider:
Type t = this.GetType();
PropertyInfo[] p = t.GetProperties();
var names = from nms in p select nms.Name;

in this case the var is not necessary

the following could be written


We need var in a case where we are using implicitly typed local variables:

this.listBox1.Items.Clear();
            Type t = this.GetType();
            PropertyInfo[] p = t.GetProperties();
            var names = from nms in p select new {Name = nms.Name,Typ =nms.PropertyType};
            foreach (var s in names)
            {
                this.listBox1.Items.Add(s.Name +" "+ s.Typ.ToString());  
            }



IEnumerable<string> names = from nms in p select nms.Name;