Suppose, We have following data source:
Now, I want to basically group these users and show the count of browser type they are using. Thus, my output should look like:
Solution:
We need to first group the data by UserIds, and from that result-set we need to again group by individual browser names (excluding their version numbers). Here is the complete code snippet:
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- public class Program
- {
- public static void Main()
- {
- List<BrowserInfo> browesers = new List<BrowserInfo>
- {
- new BrowserInfo { UserID = 1, Browser = "Chrome-32.0"},
- new BrowserInfo { UserID = 1, Browser = "Chrome-30.0"},
- new BrowserInfo { UserID = 1, Browser = "Chrome-33.0"},
- new BrowserInfo { UserID = 1, Browser = "Firefox-20.0"},
- new BrowserInfo { UserID = 1, Browser = "Firefox-26.0"},
- new BrowserInfo { UserID = 1, Browser = "Safari"},
- new BrowserInfo { UserID = 1, Browser = "IE 9"},
- new BrowserInfo { UserID = 1, Browser = "IE 10"},
- new BrowserInfo { UserID = 2, Browser = "Chrome-31.0"},
- new BrowserInfo { UserID = 2, Browser = "Chrome-32.0"},
- new BrowserInfo { UserID = 2, Browser = "IE 10"},
- new BrowserInfo { UserID = 2, Browser = "Firefox-22.0"},
- new BrowserInfo { UserID = 2, Browser = "Firefox-20.0"}
- };
-
-
- var query = from browser in browesers
- group browser by browser.UserID into UserGroup
- from countGroup in
- from brow in UserGroup
- group brow by new
- {
- Chrome = brow.Browser.Contains("Chrome"),
- Firefox = brow.Browser.Contains("Firefox"),
- IE = brow.Browser.Contains("IE")
- } into g
- select new
- {
- ChromeCount = g.Key.Chrome ? g.Count() : 0,
- FirefoxCount = g.Key.Firefox ? g.Count() : 0,
- IECount = g.Key.IE ? g.Count() : 0,
- OthersCount = (!g.Key.Chrome && !g.Key.Firefox && !g.Key.IE) ? g.Count() : 0
- }
- )
- group countGroup by UserGroup.Key;
-
- Console.WriteLine("UserId | Chrome | Firefox | IE | Others");
- Console.WriteLine("----------------------------------------");
- foreach(var users in query)
- {
- Console.WriteLine("{0} | {1} | {2} | {3} | {4} ",
- users.Key, users.Where(x => x.ChromeCount != 0).Select(x => x.ChromeCount).FirstOrDefault(),
- users.Where(x => x.FirefoxCount != 0).Select(x => x.FirefoxCount).FirstOrDefault(),
- users.Where(x => x.IECount != 0).Select(x => x.IECount).FirstOrDefault(),
- users.Where(x => x.OthersCount != 0).Select(x => x.OthersCount).FirstOrDefault()
- );
- }
-
- }
- }
-
- public class BrowserInfo
- {
- public int UserID { get; set; }
- public string Browser { get; set; }
- }
Final Output