Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable vs List

Is this is a proper use of IEnumerable or shell I use List?
what do I need to put in <PropertyInfo>?

public static IEnumerable<PropertyInfo> GetNewsList<T>(int FID)
    {
        CatomWebNetDataContext pg = (CatomWebNetDataContext)db.GetDb();
        return (from nls in pg.NewsCat_ITEMs
                  join vi in pg.VIRTUAL_ITEMs on nls.NC_VI_ID equals vi.VI_ID
                  where vi.VI_VF_ID == FID
                  select new { nls, vi });


    }

or

 public List<PropertyInfo> GetPublic<T>(int FID)
    {
        CatomWebNetDataContext pg = (CatomWebNetDataContext)db.GetDb();
        var nl = (from nls in pg.NewsCat_ITEMs
                join vi in pg.VIRTUAL_ITEMs on nls.NC_VI_ID equals vi.VI_ID
                where vi.VI_VF_ID == FID
                select new { nls, vi });

        List<PropertyInfo> retList = new List<PropertyInfo>();

        foreach (var item in nl)
        {
             retList.Add(item);
        }


        return retList;
    }
like image 364
eyalb Avatar asked Sep 24 '26 05:09

eyalb


2 Answers

The list is an instace of type, that implements IEnumerable. What it means? That if you want to return the IEnumerable<PropertyInfo> you have to create a list (or array etc.) of it and then return it.. From the outside of the method it will look like you are returning IEnumerable<PropertyInfo> but really it will be a List<PropertyInfo>.

About your query... You have to select object of type PropertyInfo, but right now you ae returning some anonymouse type. You should try it like this:

public static IEnumerable<PropertyInfo> GetNewsList<T>(int FID)
{
    CatomWebNetDataContext pg = (CatomWebNetDataContext)db.GetDb();
    var result from nls in pg.NewsCat_ITEMs
               join vi in pg.VIRTUAL_ITEMs on nls.NC_VI_ID equals vi.VI_ID
               where vi.VI_VF_ID == FID
               select new PropertyInfo { SomeMember = nls, SomeOtherMember = vi };

    return result.ToList();
}
like image 53
Łukasz W. Avatar answered Sep 25 '26 19:09

Łukasz W.


It depends on what you want to do with the result. IEnumerable basically only supports iterating over the results contained in the collection. IList is more specific, and allows you to:

  • Find out how many items are in the collection without iterating through all of them
  • Easily access an item in a specific position in the list
  • Add or remove items from the list

among other things. If you don't need the extra functionality, I would return IEnumerable. The caller of your method can easily do what you did to add the items to a List.

like image 30
Sean Reilly Avatar answered Sep 25 '26 17:09

Sean Reilly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!