Archive

Posts Tagged ‘Generics’

>C# – Returning a Generic List

August 26, 2010 Leave a comment

>Suppose I have a generic method that returns a generic list, code shows how you can do that.

public List<T> GetAll<T>() where T : class

{
   List<T> result;
   if (typeof(T) == typeof(MyObject))
   {
     result = new List<T>
      {
          new MyObject()
         {
            name = “ObjectName1”,
            id = 1
         } as T,
         new MyObject()

       {
          name = “ObjectName2”,
          id = 2
        } as T,
};
return result;
}
else //You can add other objects here if you’re using it in your Repository Test
{
return new List<T>();
}
}

Categories: .NET Development Tags:

C# – Unique List Collection

August 18, 2010 Leave a comment

C# – Unique List Collection

Ever wonder how you can create a unique list based on the certain criteria you’ve specified? See code below


/// <summary>

/// Unique Collection
/// </summary>
/// <typeparam name="T"></typeparam>
public class UniqueCollection <T> : List<T>
{
public UniqueCollection()
{
}
/// <summary>
/// Method that adds a new item if item is unique based on specified condition
/// </summary>
/// <param name="item"></param>
/// <param name="uniqueCheckCondition"></param>
/// <returns>Returns true if item is added to the collection</returns>
public bool AddUniqueValue(T item, Predicate<T> uniqueCheckCondition)
{
bool isAdded = true;
foreach(T i in this)
{
if (uniqueCheckCondition(i))
{
isAdded = false;
break;
}
}

if (isAdded)
{
this.Add(item);
}
return isAdded;
}
}

Sample use:


Guid dupGuid = Guid.NewGuid();

TestClass item1 = new TestClass
{
GUID = dupGuid.ToString() ,
SettingReference = "Test"
};

TestClass item2 = new TestClass
{
GUID = dupGuid.ToString(),
SettingReference = "Test"
};

UniqueCollection<TestClass> target = new UniqueCollection<TestClass>();
target.AddUniqueValue(item1, i => i.GUID == item1.GUID);
target.AddUniqueValue(item2, i => i.GUID == item2.GUID);
Assert.AreEqual(1, target.Count);
%d bloggers like this: