write a function using generic

Posted by user296551 on Stack Overflow See other posts from Stack Overflow or by user296551
Published on 2010-03-18T14:01:35Z Indexed on 2010/03/18 14:11 UTC
Read the original article Hit count: 146

Filed under:
|

hi,guy, i want write a function using c#, and it accept any type parameter,i want use generic list to do, but i can't finish, it's wrong, how to do it? perhaps there are other ways??

thinks!

public class City
{
    public int Id;
    public int? ParentId;
    public string CityName;
}

public class ProductCategory
{
    public int Id;
    public int? ParentId;
    public string Category;
    public int Price;
}

public class Test
{

        public void ReSortList<T>(IEnumerable<T> sources, ref IEnumerable<T> returns, int parentId)
        {
           //how to do like this:
           /*
            var parents = from source in sources where source.ParentId == parentId && source.ParentId.HasValue select source;

            foreach (T child in parents)
            {
                returns.Add(child);
                ReSortList(sources, ref returns, child.Id);
            }
           */
        }

        public void Test()
        {
            IList<City> city = new List<City>();

            city.Add(new City() { Id = 1, ParentId = 0, CityName = "China" });
            city.Add(new City() { Id = 2, ParentId = null, CityName = "America" });
            city.Add(new City() { Id = 3, ParentId = 1, CityName = "Guangdong" });

            IList<City> results = new List<City>();
            ReSortList<City>(city, ref results, 0);  //error
        }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about generic