【问题标题】:Iterating through a generic list property遍历通用列表属性
【发布时间】:2017-10-14 18:49:11
【问题描述】:

所以我有课

public class SearchViewModel<T> where T:class
    {
        public string LastSortColumn { get; set; }
        public string LastSortDirection { get; set; }
        public List<T> SearchItems;
        public SearchViewModel(List<T> SearchItems)
        {
            this.SearchItems = SearchItems;
        }
    }

有什么方法可以使用 foreach 循环或其他方式遍历属性 SearchItems 吗? PS:SearchViewModel 也是我的模型

【问题讨论】:

  • 当然,foreach(var element in SearchItems) { ... }`。老实说:为什么不谷歌“如何在 c# 中迭代​​列表”?
  • @HimBromBeere 是的,但 SearchViewModel 也是我的模型
  • @john 为什么这会阻止您使用 Google?
  • @john 考虑到您的问题的“答案”是您在搜索结果中看到的数十万次,如果您实际搜索过您的问题,是的,很明显你来这里之前没有搜索。您似乎误以为本网站上的每个人都是您的奴隶,而我们的存在纯粹是为了为您服务。这完全是错误的。我们不存在只是为了让您在有问题时不必费心使用 Google。
  • @Servy 奇怪的是,帮助我的人投了反对票……太可怜了

标签: c# asp.net-mvc oop asp.net-mvc-5


【解决方案1】:

在此处使用 var,编译器将在 foreach 循环中决定列表中 SearchItem 的类型。在这个例子中 var 的类型是 string/

     SearchViewModel<string> vs = new SearchViewModel<string>(new List<string> { "1","2","3"});

     foreach (var item in vs.SearchItems)
     {
        // logic, item in this case is string 
     }  

【讨论】:

    猜你喜欢
    • 2019-01-25
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多