Home > Mobile >  Linq query GroupBy value and determine if value meets multiple criteria
Linq query GroupBy value and determine if value meets multiple criteria

Time:09-03

Scandata has two fields, hostname and pluginID. There are numerous pluginids listed for each hostname. In this query, I'm trying to return scanstatus as true for a host when both pluginids are assigned to that host. If only one or none is found, return false. I'm missing something here, but I'm not sure what. This returns false whether one or both pluginids are listed for a given host.

        var goodscan = scandata.AsEnumerable()
            .GroupBy(g => g.hostname)
            .Select(s => new
            {
                hostname = s.Key,
                scanstatus = s.All(v => v.pluginid.Contains("19506") && v.pluginid.Contains("117887"))
            })
            .ToList();

CodePudding user response:

Your Enumerable.All query checks if ALL scans in each host-group have a pluginid which contains "19506" AND "117887"at the same time. Thats incorrect.

You want to know for each hostname-group if there is at least ONE scan with pluginid "19506" and ANOTHER with "117887", so use Any instead of All:

var goodscan = scandata.AsEnumerable()
    .GroupBy(g => g.hostname)
    .Select(s => new
    {
        hostname = s.Key,
        scanstatus = s.Any(v => v.pluginid.Contains("19506")) 
                  && s.Any(v => v.pluginid.Contains("117887"))
    })
    .ToList();
  •  Tags:  
  • linq
  • Related