I am curious on how the following code works, especially the part the contains the delegate stuff since I am new to it. Also, are there any bottlenecks in the code, for example, would using a SortedDictionary be better than using a List and then sorting it using LINQ? Ok, here is the code:
public class ColorManager { private List<ColorData> colorCodes = new List<ColorData>(); public List<ColorData> ColorCodes { get { var sortList = from a in this.colorCodes orderby a.colorCode ascending select a; return sortList.ToList(); } } public void FillData(DataTable table) { for(int row = 0; row < table.Rows.Count; row++) { ColorData cData = new ColorData(); string name = table.Rows[row]['Color'].ToString().Trim(); if(!this.colorCodes.Exists( delegate(ColorData e) { return e.ColorCode == name; })) { cData.Add(table.Rows[row]['Color'].ToString()); this.colorCodes.Add(cData); } else { this.colorCodes.Find( delegate(ColorData e) { return e.ColorCode == name; }).Count++; } } } }
First take a look at this
ColorCodesproperty accessor:It returns a list of all the color codes (
this.colorCodes) in ascending order (...orderby a.colorCode ascending). Simple so far. How about the meatierFillDatamethod?First, we’ll loop over every row in this table:
Then, we’re going to look at the
Colorcolumn of the current row.If that column has no match in our list of color codes, this
ifcondition is true. TheExistsmethod takes a single-argument function that returns a bool, which is what this anonymous delegate is: a single-argument (ColorData e) function that returns a boolean (e.ColorCode == name). It gets negated (!this.[...]), so if a match is found, the condition is false.Otherwise, if there’s a match, find the name using another anonymous delegate, and add one to the count of items of that color.
Note that this code is somewhat inefficient, since the two different anonymous delegates really do the same thing and could be shared.