3

我有一个 ArrayList 类型RawResultsRawResults位置和日期

public class RawResult
{
    public string location { get; set; }
    public DateTime createDate {get; set; }

    public RawResults(string l, DateTime d)
    {
        this.location = l;
        this.createDate = d;
    }
}

我想使用 LINQ 填充一个列表,其中包含每个不同的位置以及它在我的数组列表中出现的次数。如果我能够在 SQL 中做到这一点,它看起来像这样

select 
   bw.location, 
   count(*) as Count
from 
   bandwidth bw, 
   media_log ml
where
   bw.IP_SUBNET = ml.SUBNET
   group by bw.location
   order by location asc

以后我也必须在给定的日期范围内做同样的事情。

UPDATE 这是为获取所有数据而运行的查询rawData

SELECT        
    MEDIASTREAM.BANDWIDTH.LOCATION, MEDIASTREAM.MEDIA_LOG.CREATE_DATE
FROM            
    MEDIASTREAM.BANDWIDTH INNER JOIN
      MEDIASTREAM.MEDIA_LOG ON MEDIASTREAM.BANDWIDTH.IP_SUBNET =     
      MEDIASTREAM.MEDIA_LOG.SUBNET

现在我需要查询返回的数据rawData以获得不同的结果集。我有一个可供查询的列表。

4

2 回答 2

6

你可以这样做:

var results = 
    (from bw in data.bandwith
     join ml in data.media_log on bw.IP_SUBNET equals ml.SUBNET
     group bw by bw.location into g
     orderby g.Key
     select new 
     { 
         location = g.Key, 
         Count = g.Count() 
     })
    .ToList();

虽然ToList除非你绝对需要它是一个List<T>. 要按时间过滤,您可以执行以下操作:

var results = 
    (from bw in data.bandwith
     join ml in data.media_log on bw.IP_SUBNET equals ml.SUBNET
     where bw.createDate >= minDate && bw.createDate <= maxDate
     group bw by bw.location into g
     orderby g.Key
     select new 
     { 
         location = g.Key, 
         Count = g.Count() 
     })
    .ToList();

如果media_log不相关,您可以省略join

var results = 
    from bw in data.bandwith
    group bw by bw.location into g
    orderby g.Key
    select new 
    { 
        location = g.Key, 
        Count = g.Count() 
    }

或流利的语法:

var results = data.bandwith
    .GroupBy(bw => bw.location, (k, g) => new { location = k, Count = g.Count() })
    .OrderBy(r => r.location);

要按日期过滤,只需使用以下命令:

var results = 
    from bw in data.bandwith
    where bw.createDate >= minDate && bw.createDate <= maxDate
    group bw by bw.location into g
    orderby g.Key
    select new 
    { 
        location = g.Key, 
        Count = g.Count() 
    };

或流利的语法:

var results = data.bandwith
    .Where(bw => bw.createDate >= minDate && bw.createDate <= maxDate)
    .GroupBy(bw => bw.location, (k, g) => new { location = k, Count = g.Count() })
    .OrderBy(r => r.location);

请注意,要ArrayList在 Linq 查询中使用 或任何其他非泛型集合类型,请使用Cast<T>orOfType<T>方法,如下所示:

var results = bandwithArrayList
    .Cast<RawResults>()
    .GroupBy(bw => bw.location, (k, g) => new { location = k, Count = g.Count() })
    .ToList();
于 2013-06-18T18:52:27.887 回答
3
List<RawResult> results = MethodToGetResults();

var locationCount = results
     .GroupBy(r => r.location)
     .Select(lc => new {Location = lc.location, Count = lc.Count()});
于 2013-06-18T18:54:19.783 回答