Wednesday, May 18, 2011

Some Fun With Linq.

A friend of mine was asking me how I search through dictionary that contain lists of objects with Linq. After I chatted with him for a bit. I realized I don't do that.  I have one huge list that I parse out with linq.  It makes my life easier.  Here is a code example of what I would use.


        public class section
        {
            public string Group { getset; }
            public string Order { getset; }
            public string Section { getset; }
            public string Title { getset; }
        }
 
        static void Main(string[] args)
        {
            var sec = new List<section>();
            sec.Add(new section { Group = "1", Order = "1", Section = "1.1", Title = "one one" });           
            sec.Add(new section { Group = "1", Order = "3", Section = "1.3", Title = "one three" });
            sec.Add(new section { Group = "1", Order = "2", Section = "1.2", Title = "one two" });
            sec.Add(new section { Group = "2", Order = "1", Section = "2.1", Title = "two one" });
            sec.Add(new section { Group = "2", Order = "2", Section = "2.2", Title = "two two" });
            sec.Add(new section { Group = "3", Order = "1", Section = "3.1", Title = "three one" });
 
            //creates a diction with all the sections in order grouped by group.
            var jmp = sec.OrderBy(j => j.Order).GroupBy(c => c.Group).ToDictionary(c => c.Key, d => d.ToList());
            //gets one section form a section
            var wantedSection = sec.FirstOrDefault(c => c.Section == "2.2");  //return null if no iteem found
            //gets one section in the order you set in order
            var sectionOne = sec.Where(c => c.Group == "1").OrderBy(c => c.Order).ToList();                        
        }