Unable to use use .Except on two List<String>

I am working on an asp.net mvc-5 web applicatio. i have these two model classes:-

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

and i have the following method:-

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

now i want to get all the String that are inside the allcurrentrecoursename list but not inside the CurrentresourcesName ?

but that above code is raising the following exceptions :-

Error 4 'System.Collections.Generic.List>' does not contain a definition for 'Except' and the best extension method overload 'System.Linq.Queryable.Except(System.Linq.IQueryable, System.Collections.Generic.IEnumerable)' has some invalid arguments

Error 3 Instance argument: cannot convert from 'System.Collections.Generic.List>' to 'System.Linq.IQueryable'


It looks to me like

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

is not a list of strings at all like you seem to expect it to be. scaninfo is of type List<ScanInfo> , and the lambda expression

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

yields one IEnumerable<TSomething> for each ScanInfo object. So it would seem that allcurrentresourcename is not a List<string> , but rather a List<IEnumerable<TSomething>> , where TSomething is the type of RESOURCENAME (most likely string ).

Edit: What you presumably want to use here is the SelectMany LINQ method (see @pquest's comment). It flattens the lists that you get to "one big list" of resource names, which you can then use Except on:

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

You shouldn't even need the ToList() at the end of the line.

链接地址: http://www.djcxy.com/p/75254.html

上一篇: 左外连接lambda表达式错误

下一篇: 无法使用use.Except两个List <String>