eyalb
eyalb

Reputation: 3022

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;
    }

Upvotes: 3

Views: 6484

Answers (3)

Mark LeMoine
Mark LeMoine

Reputation: 4618

You're able to return a List<PropertyInfo>, given that it's an implementation of IEnumerable<PropertyInfo>. The only thing will be that it will look like a plain old IEnumerable to the caller function once it returns.

Upvotes: 0

Sean Reilly
Sean Reilly

Reputation: 21836

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.

Upvotes: 3

Łukasz W.
Łukasz W.

Reputation: 9755

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();
}

Upvotes: 3

Related Questions