Monday 3 October 2011

How to get comma separated string from the list of object for specified property

I have a one requirement that I have list of objects with that object have properties(ID, Name, Description). I want a comma separated string from the list of object for ID property.
We can achieve this by using Reflection classes.

The solution for the requirement has follows

Create a generic method to get the Comma separated string
 public static string GetCommaSeparatedString<T>(List<T> list, string property)
        {
                string value = string.Empty;
                PropertyInfo info = typeof(T).GetProperties().Where(i => i.Name == property).FirstOrDefault();
                if (info != null)
                {
                    foreach (T listItem in list)
                    {
                        value += info.GetValue(listItem, null).ToString() + ",";
                    }
                }
            return value.Substring(0,value.Length-1);
        }
Usage:
Take an example with Category class with the properties ID,Name
public class Category
{      
    public int ID { get; set; }
    public string Name { get; set; }
}
Create a list with Category objects
List<category> categories=new List<category>();
categories.Add(new Catagory {ID=1, Name = "abc" });
categories.Add(new Catagory {ID=10, Name = "pqr" });
Call the method as follows
GetCommaSeparatedString<Category>(categories,"ID");
//output: 1,10

No comments:

Post a Comment