Generic Collections – Contains via LINQ

A very quick blog post as I seem to be quite busy at the moment.

I was working with a colleague last week and we implemented a generic collection to store a couple of names. Due to time constraints (and a little bit of laziness) in order to detect the presence of a name, I quickly implemented a for loop to scan through the collection in order to find out if it contained the item I was after.

I made a promise to investigate how to do this properly, and have spent a little time this morning investigating the proper answer.

So, with some very quick code examples, our person matching object:

public class PersonMatcher
{
   public string Employee {get; set;}
   public string Boss {get; set;}

   public PersonMatchers(string emp, string boss)
   {
      Employee = emp;
      Boss = boss;
   }
}

Then our little holder object which performs business logic on the list (note, simplified example for clarity) – including the isBossPresent() function to detect whether the ‘boss’ is included in the List:

public class EmployeeList
{
   private List<PersonMatcher> PersonMatcherList;

   public EmployeeList()
   {
      PersonMatcherList = new List<PersonMatcher>();
      PersonMatcherList.Add(new PersonMatchers(“Emp1”, “Boss1”));
      PersonMatcherList.Add(new PersonMatchers(“Emp2”, “Boss1”));
      PersonMatcherList.Add(new PersonMatchers(“Emp3”, “Boss2”));
   }

   public bool IsBossPresent(string bossName)
   {
      return PersonMatcherList.Exists((x => x.Boss == bossName));}
   }

Then a very simple Program.cs to test the functionality:

EmployeeList ml = new EmployeeList();

if (ml.IsBossPresent("Boss1"))
{
   Console.WriteLine("Found Boss1!");
}
else
{
   Console.WriteLine("Didn't find Boss1! BUG");
}

if (ml.IsBossPresent("Boss22"))
{
   Console.WriteLine("Found Boss22 as marker! BUG");
}
else
{
   Console.WriteLine("Didn't find Boss22 as marker!");
}

Console.ReadLine();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s