我有一个类型为 RawResults
的 ArrayList,其中 RawResults
是位置和日期
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
稍后我也必须做同样的事情,但在给定的日期范围内。
更新
这是为获取 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
中返回的数据以获得不同的结果集。我有一个列表可供查询。
最佳答案
你可以这样做:
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>
或 OfType<T>
方法,像这样:
var results = bandwithArrayList
.Cast<RawResults>()
.GroupBy(bw => bw.location, (k, g) => new { location = k, Count = g.Count() })
.ToList();
关于c# - 使用 LINQ 填充列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176533/