Friday, May 31, 2013

Get String From Collectoin Specific class attribute

Sometimes we need to get a specific atribute values of a collection of any class. In this case we use this generic method. 
//Here Source means collection, valueField means the attribute which we supplied
public static string GetStringFromCollectionAttribute<T>(this ObservableCollection<T> source, string valueField)

{


try

{


string returnString = String.Empty;


if (source.Count > 0)

{


foreach (var obj in source)

{


if (returnString == "") {

returnString = obj.GetType().GetProperty(valueField).GetValue(obj,
null).ToString();

}


else

{

returnString = returnString +

"," + obj.GetType().GetProperty(valueField).GetValue(obj, null);

}

}


if (returnString == String.Empty)

{

returnString = returnString.Substring(0, returnString.Length - 1);

}

}


return returnString;

}


catch (Exception ex)

{


throw ex;

}

}
 

//calling part



ObservableCollection<Student> StudentList = new ObservableCollection<Student>{


new Student {Id=1,Name = "Pria"},


new Student {Id=2,Name = "Smith"},


new Student {Id=3,Name = "Devid"},


new Student {Id=4,Name = "Helen"},


new Student {Id=5,Name = "Nuton"},


new Student {Id=6,Name = "Kafre"},

};


//If I want to get all of the student name from the list as a string I just call the following function


string StudentNames = Extention.GetStringFromCollectionAttribute(StudentList, "Name");

No comments:

Post a Comment