我的数据表(DeviceInfo):
ID | OS | Device ----------------------------------------------- 1 | Android 2.2 | Samsung 2 | Linux/Android 4.2 | LG 3 | Linux/Android 4.4.2 | HTC 4 | Android 3.2 | Samsung 5 | Android 3.0 | Motorola 6 | iOS 7.1.2 | iPad 7 | iOS 8.0 | iPhone 6 8 | iOS 6.1.6 | iPhone 4
我想使用Linq对Android和ios用户对此表进行分组。实际上我必须使用子串“Android”和“iOS”对表进行分组。
我的输出应该是
ID | User | Count ---------------------------- 1 | Android | 5 2 | iOS | 3
我如何使用linq获取此表?
答案 0 :(得分:2)
您可以尝试这样的事情:
// db is my datacontext
var groupByOS = (from c in
(from d in db.DeviceInfo
where d.Os.ToUpper().Contains("ANDROID") ||
d.Os.ToUpper().Contains("IOS")
group d by new { d.Os } into dev
select new
{
User = dev.Key.Os.ToUpper().Contains("ANDROID") ? "Android" : "iOS",
DeviceCount = dev.Count()
})
group c by new { c.User } into newgrp
select new
{
newgrp.Key.User,
Count = newgrp.Sum(q => q.DeviceCount)
}).ToList();
答案 1 :(得分:2)
试试这个:(我用过Console App,你可以根据你的要求改变它): -
var query = from device in deviceInfo
where device.OS.Contains("Android") || device.OS.Contains("iOS")
group device by new { Android = device.OS.Contains("Android"), iOS = device.OS.Contains("iOS") } into deviceGroup
select new
{
AndroidCount = deviceGroup.Key.Android ? deviceGroup.Count() : 0,
iOSCount = deviceGroup.Key.iOS ? deviceGroup.Count() : 0
};
Console.WriteLine("User | Count");
Console.WriteLine("--------------");
foreach (var dev in query)
{
if (dev.AndroidCount != 0)
Console.WriteLine("{0} | {1}", "Android", dev.AndroidCount);
if(dev.iOSCount!=0)
Console.WriteLine("{0} | {1}", "iOS", dev.iOSCount);
}