public static string ExportCommentsOnPosts(InstagraphContext context) { using (context) { var users = context.Users .Select(x => new { Username = x.Username, PostCommentsCount = x.Posts.Select(p => p.Comments.Count).ToArray() }); var userList = new List <UserMostCommentsDto>(); var xmlDoc = new XDocument(new XElement("users")); foreach (var user in users) { int mostComments = 0; if (user.PostCommentsCount.Any()) { mostComments = user.PostCommentsCount.OrderByDescending(x => x).First(); } var newUser = new UserMostCommentsDto() { Username = user.Username, MostComments = mostComments }; userList.Add(newUser); } userList = userList.OrderByDescending(x => x.MostComments) .ThenBy(x => x.Username) .ToList(); foreach (var user in userList) { xmlDoc.Root.Add(new XElement("user", new XElement("Username", user.Username), new XElement("MostComments", user.MostComments))); } var result = xmlDoc.ToString(); return(result); } }
public static string ExportCommentsOnPosts(InstagraphContext context) { var users = context.Users .Select(u => new { Username = u.Username, CommentsCount = u.Posts.Select(p => p.Comments.Count).ToArray() }) .ToArray(); var userDtos = new List <UserMostCommentsDto>(); foreach (var u in users) { var mostComments = 0; if (u.CommentsCount.Any()) { mostComments = u.CommentsCount.OrderByDescending(x => x).First(); } var userDto = new UserMostCommentsDto() { Username = u.Username, MostComments = mostComments }; userDtos.Add(userDto); } var xDoc = new XDocument(new XElement("users")); foreach (var user in userDtos.OrderByDescending(u => u.MostComments).ThenBy(u => u.Username)) { xDoc.Root.Add(new XElement("user", new XElement("Username", user.Username), new XElement("MostComments", user.MostComments))); } return(xDoc.ToString()); }