在 Foreach 中切换集合

Switch Collection In a Foreach

这两个集合都有 ExternalId。我将如何更改 foreach 使用的集合,具体取决于参数类型是 1 还是 2。我必须执行两个单独的循环还是可以以某种方式使用集合 T?

        public ActionResult Details(string id, int type)
        {
           IEnumerable<Album> collection1 = ASR.Albums;
           IEnumerable<Track> collection2 = TSR.Tracks;


           foreach (var item in collection1)
           {
               var result = item.ExternalIds.SingleOrDefault(x => x.Id == id);
               if (result != null)
               {
                   return View(item);
               }
           }
           return View();
        }

创建一个以 ExternalIds 作为成员的接口,让 Album 和 Track 从该接口派生。

    public interface IExternalIds
    {
        public IEnumerable<SomeType> ExternalIds { get; }
    }

    public class Album: IExternalIds
    {
        ...
    }

    public class Track: IExternalIds
    {
        ...
    }

    public ActionResult Details(string id, int type)
    {
       IEnumerable<Album> collection1 = ASR.Albums;
       IEnumerable<Track> collection2 = TSR.Tracks;
       var collectionToUse = ((type == 1) ? collection1 : collection2)
        as IEnumerable<IExternalIds>;

       foreach (var item in collectionToUse)
       {
           var result = item.ExternalIds.SingleOrDefault(x => x.Id == id);
           if (result != null)
           {
               return View(item);
           }
       }
       return View();
    }

我认为你希望他们有一个基地 class/interface。让我为您举例说明:

public interface IEntity
{
    public List<YourListType> ExternalIds { get; set; }
}

然后在 类:

中实现 IEntity 接口
public class Album : IEntity
{
    public List<YourListType> ExternalIds { get; set; }
}

完成后,您的代码将如下所示:

    public ActionResult Details(string id, int type)
    {
       IEnumerable<IEntity> collection1 = ASR.Albums;
       IEnumerable<IEntity> collection2 = TSR.Tracks;
       var collectionToUse = (type == 1) ? collection1 : collection2;

       foreach (var item in collectionToUse)
       {
           var result = item.ExternalIds.SingleOrDefault(x => x.Id == id);
           if (result != null)
           {
               return View(item);
           }
       }
       return View();
    }

因此,通过实现一个将在 类 中实现的接口,您可以使用在接口中声明的公共属性

我希望这能回答你的问题。

专辑和曲目有共同的基本类型吗?如果是这样,您可以这样做:

IEnumerable<BaseType> collection = type == 1 ? ASR.Albums : TSR.Tracks;
foreach (var item in collection)
{
   ...
}

如果您没有通用基类型,请创建一个接口,在 foreach 中添加您需要的通用属性,将其应用于 AlbumTrack,然后执行一些操作像这样:

IEnumerable<IMusicInfo> collection = type == 1 ? ASR.Albums : TSR.Tracks;
foreach (var item in collection)
{
   ...
}

请记住为您的界面命名并仅添加在该界面中有意义的属性以获得良好的编码实践