无法使用。除了两个List <string>

时间:2015-10-19 14:05:25

标签: c# asp.net-mvc entity-framework entity-framework-6

我正在开发一个asp.net mvc-5 web应用程序。我有这两个模型类: -

public class ScanInfo
    {
        public TMSServer TMSServer { set; get; }
        public Resource Resource { set; get; }
        public List<ScanInfoVM> VMList { set; get; }
    }



 public class ScanInfoVM
    {
        public TMSVirtualMachine TMSVM { set; get; }
        public Resource Resource { set; get; }
    }

我有以下方法: -

    List<ScanInfo> scaninfo = new List<ScanInfo>();

    List<String> CurrentresourcesNames = new List<String>();


    for (int i = 0; i < results3.Count; i++)//loop through the returned vm names
         {


            var vmname = results3[i].BaseObject == null ? results3[i].Guest.HostName : results3[i].BaseObject.Guest.HostName;//get the name

            if (!String.IsNullOrEmpty(vmname))
                 {
                   if (scaninfo.Any(a => a.VMList.Any(a2 => a2.Resource.RESOURCENAME.ToLower() == vmname.ToLower())))

                       {

                         CurrentresourcesNames.Add(vmname);
                       }   

                  }

        }
  var allcurrentresourcename = scaninfo.Select(a => a.VMList.Select(a2 => a2.Resource.RESOURCENAME)).ToList();
  var finallist = allcurrentresourcename.Except(CurrentresourcesNames).ToList();

现在我想获取allcurrentrecoursename列表中但不在CurrentresourcesName内的所有字符串?

但上述代码引发了以下例外情况: -

  

错误4'System.Collections.Generic.List&gt;'   不包含'Except'的定义和最佳扩展名   方法过载   “System.Linq.Queryable.Except(System.Linq.IQueryable,   System.Collections.Generic.IEnumerable)'有一些无效   参数

     

错误3实例参数:无法转换   'System.Collections.Generic.List&GT;'   到'System.Linq.IQueryable'

1 个答案:

答案 0 :(得分:1)

在我看来像是

var allcurrentresourcename = scaninfo.Select(a => a.VMList.Select(a2 => a2.Resource.RESOURCENAME)).ToList();

根本不是你想象的字符串列表。 scaninfo的类型为List<ScanInfo>,lambda表达式为

a => a.VMList.Select(a2 => a2.Resource.RESOURCENAME)

为每个IEnumerable<TSomething>对象生成一个ScanInfo。因此allcurrentresourcename似乎不是List<string>,而是List<IEnumerable<TSomething>>,其中TSomethingRESOURCENAME的类型(最有可能string })。

编辑:你在这里想要使用的是SelectMany LINQ方法(参见@pquest的评论)。它会使您获得资源名称“一大列表”的列表变得扁平化,然后您可以使用Except

var allcurrentresourcename = scaninfo.SelectMany(a => a.VMList.Select(
    b => b.Resource.RESOURCENAME));

你甚至不需要行尾的ToList()