我有一个包含2列的数据表:
GuitarBrand | Status
---------------------
Fender | Sold
Fender | In Stock
Gibson | In Stock
Gibson | In Stock
我想写一个linq查询来输出
GuitarBrand | PercentSold | Sold/Total
---------------------------------------
Fender | 50% | 1/2
Gibson | 100% | 2/2
这是我到目前为止所拥有的:
var groupedtable = from b in table.AsEnumerable()
group b by b.Field<"GuitarBrand"> into g
select new ( GuitarBrand = g.Key, Perecent = (float)g.Count()/(float)g.key)
我从另一篇文章得到的但是它甚至没有接近工作,我得到一个无法转换字符串浮动。我试过看其他帖子但我找不到任何东西。
谢谢!
答案 0 :(得分:1)
也许是这样的!
var groupedtable = from b in table.AsEnumerable()
group b by b.Field<"GuitarBrand"> into g
select new {
GuitarBrand = g.Key,
Perecent = g.Count(x=>x.Status.Eguals("Sold")/(float)g.Count()
}
答案 1 :(得分:1)
您可以使用以下(希望自我解释)查询:
var groupedtable =
from b in table.AsEnumerable()
group b by b.Field<string>("GuitarBrand") into g
let Total = g.Count()
let Sold = g.Count(e => e.Field<string>("Status") == "Sold")
let SoldPercent = (float)Sold / (float)Total
select new
{
GuitarBrand = g.Key,
PercentSold = SoldPercent.ToString("p"),
TotalSold = Sold + "/" + Total
};
答案 2 :(得分:0)
这样的事情应该让你开始。在您的问题中,您的输出表是矛盾的。我假设你想要标记数据。
public static void Main()
{
var guitars = new List<Guitar>()
{
new Guitar(){ Brand = "Fender", Status = Status.Sold },
new Guitar(){ Brand = "Fender", Status = Status.InStock },
new Guitar(){ Brand = "Gibson", Status = Status.InStock },
new Guitar(){ Brand = "Gibson", Status = Status.InStock }
};
var query = guitars
.GroupBy(guitar => guitar.Brand)
.Select(group => new
{
GuitarBrand = group.Key,
Sold = group.Where(guitar => guitar.Status == Status.Sold).Count(),
Total = group.Count()
})
.Select(_ => new
{
_.GuitarBrand,
PercentSold = ((decimal)_.Sold / (decimal)_.Total) * 100,
SoldAndTotal = string.Format("{0}/{1}", _.Sold, _.Total)
});
}
class Guitar {
public string Brand { get; set; }
public Status Status { get; set; }
}
enum Status {
Sold,
InStock
}