MSDN’s documentation for the List(T).Find method shows a clean and concise example of finding a string in a List<string>. However it is not helpful when you want to locate a custom object in a List<> of custom objects. For that we need to create a delegate method. The following example uses an anonymous delegate method for a cleaner coding approach. It’s been tested in Snippet Compiler 2.0.8.3.
1: using System;
2: using System.Collections.Generic;
3:
4:
5:
6: /// <summary>
7: /// Demonstration using delegate method to find custom object in List<>
8: /// </summary>
9: public class MyClass {
10: public static List<Dept> Depts = new List<Dept>();
11:
12: public static void Main() {
13: Dept dept = new Dept();
14:
15: // We seed the List<> with some departments for demo purposes
16: Depts.Add(new Dept("sales"));
17: Depts.Add(new Dept("marketing"));
18: Depts.Add(new Dept("accounting"));
19:
20:
21: // Assume input for next two blocks came from a db query, user input, etc
22: dept = Dept.GetByName(Depts, "sales");
23: if(dept == null) {
24: dept = new Dept("sales");
25: Depts.Add(dept);
26: }
27:
28: dept = Dept.GetByName(Depts, "production");
29: if(dept == null) {
30: dept = new Dept("production");
31: Depts.Add(dept);
32: }
33:
34:
35: // Iterate Depts<> and echo out departments. Note that sales did not get
36: // added a second time
37: foreach(Dept d in Depts) {
38: WL(d.DeptName + "\n");
39: }
40:
41: // Hit enter to close the console
42: RL();
43: }
44:
45:
46:
47: #region Helper methods
48:
49: private static void WL(object text, params object[] args) {
50: Console.WriteLine(text.ToString(), args);
51: }
52:
53: private static void RL() {
54: Console.ReadLine();
55: }
56:
57: private static void Break() {
58: System.Diagnostics.Debugger.Break();
59: }
60:
61: #endregion
62: }
63:
64:
65:
66: /// <summary>
67: /// Simple Class implements a department object with just name and id plus a
68: /// delegate method GetByName() that returns an object from a List<> based on
69: /// the objects DeptName property.
70: /// </summary>
71: public class Dept {
72: public string DeptName;
73: public long DeptId;
74:
75: public Dept() {
76: }
77:
78: public Dept(string deptName) {
79: DeptName = deptName;
80: }
81:
82: // Returns the first occurance of an object containing the deptName or null
83: // if it does not exist
84: public static Dept GetByName(List<Dept> list, string deptName) {
85: return list.Find(delegate(Dept obj) {
86: return obj.DeptName == deptName;
87: });
88: }
89: }