简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM