>C# – Getting Property value of an object using extension method

>Code below illustrate how to process a list of T and validating or checking the value of one of the property of object T using C# 3.0 extension methods.

///



/// Method that returns Value of Property from an Object
///

///
///
///
public static string GetPropertyValue(this object obj, string propertyName)
{
if (obj == null)
{
throw new ArgumentNullException(“obj”);
}
PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
object prop = propertyInfo.GetValue(obj, null);
return prop.ToString();
}
else
{
return string.Empty;
}
}
 
 
Sample Usage:

///



//////

[TestMethod()]
public void GetPropertyValueTest()
{
List list = new List
{
new TestClass
{
GUID = “Not this value”
},
new TestClass
{
GUID = “ThisValue”
}
};
ProcessList(list);
}


private void ProcessList(List list) where T: class
{
//Check the value of certain property in T object
var query = list.Find(i => i.GetPropertyValue(“GUID”) == “ThisValue”);
if(query != null)
{
//Match Found.. Do processing here
}
else
{
//No Match found..
}
}

C# – Unique List Collection

C# – Unique List Collection

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


/// 

/// Unique Collection
/// 
/// 
public class UniqueCollection  : List
{
public UniqueCollection()
{
}
/// 
/// Method that adds a new item if item is unique based on specified condition
/// 
/// 
/// 
/// Returns true if item is added to the collection
public bool AddUniqueValue(T item, Predicate 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 target = new UniqueCollection();
target.AddUniqueValue(item1, i => i.GUID == item1.GUID);
target.AddUniqueValue(item2, i => i.GUID == item2.GUID);
Assert.AreEqual(1, target.Count);