Skip to content

Commit

Permalink
improved some LINQ expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
ThisWillDoIt committed Oct 4, 2016
1 parent 9bccf0e commit 166a4ca
Show file tree
Hide file tree
Showing 30 changed files with 66 additions and 68 deletions.
6 changes: 3 additions & 3 deletions BlogEngine/BlogEngine.Core/Data/BlogRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public Models.Blog FindById(Guid id)
if (!(Blog.CurrentInstance.IsPrimary && Security.IsAdministrator))
throw new UnauthorizedAccessException();

var blog = Blog.Blogs.Where(b => b.Id == id).FirstOrDefault();
var blog = Blog.Blogs.FirstOrDefault(b => b.Id == id);
return ToJson(blog);
}

Expand Down Expand Up @@ -92,7 +92,7 @@ public bool Update(Models.Blog blog)
throw new UnauthorizedAccessException();
try
{
var coreBlog = Blog.Blogs.Where(b => b.Id == blog.Id).FirstOrDefault();
var coreBlog = Blog.Blogs.FirstOrDefault(b => b.Id == blog.Id);
return Save(coreBlog, blog);
}
catch (Exception)
Expand All @@ -113,7 +113,7 @@ public bool Remove(Guid id)
throw new UnauthorizedAccessException();
try
{
var blog = Blog.Blogs.Where(b => b.Id == id).FirstOrDefault();
var blog = Blog.Blogs.FirstOrDefault(b => b.Id == id);
blog.Delete();
blog.Save();
return true;
Expand Down
6 changes: 3 additions & 3 deletions BlogEngine/BlogEngine.Core/Data/CategoryRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public IEnumerable<CategoryItem> Find(int take = 10, int skip = 0, string filter
// add categories without posts
foreach (var c in Category.Categories)
{
var x = items.Where(i => i.Id == c.Id).FirstOrDefault();
var x = items.FirstOrDefault(i => i.Id == c.Id);
if (x == null)
items.Add(new CategoryItem { Id = c.Id, Parent = OptionById(c.Parent), Title = c.Title, Description = c.Description, Count = 0 });
}
Expand Down Expand Up @@ -87,11 +87,11 @@ public CategoryItem FindById(Guid id)
// add categories without posts
foreach (var c in Category.Categories)
{
var x = items.Where(i => i.Id == c.Id).FirstOrDefault();
var x = items.FirstOrDefault(i => i.Id == c.Id);
if (x == null)
items.Add(new CategoryItem { Id = c.Id, Parent = OptionById(c.Parent), Title = c.Title, Description = c.Description, Count = 0 });
}
return items.Where(c => c.Id == id).FirstOrDefault();
return items.FirstOrDefault(c => c.Id == id);
}
/// <summary>
/// Add new item
Expand Down
4 changes: 2 additions & 2 deletions BlogEngine/BlogEngine.Core/Data/CommentsRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public CommentItem Add(CommentDetail item)
var c = new Comment();
try
{
var post = Post.Posts.Where(p => p.Id == item.PostId).FirstOrDefault();
var post = Post.Posts.FirstOrDefault(p => p.Id == item.PostId);

c.Id = Guid.NewGuid();
c.ParentId = item.ParentId;
Expand All @@ -104,7 +104,7 @@ public CommentItem Add(CommentDetail item)
post.AddComment(c);
post.Save();

var newComm = post.Comments.Where(cm => cm.Content == c.Content).FirstOrDefault();
var newComm = post.Comments.FirstOrDefault(cm => cm.Content == c.Content);
return Json.GetComment(newComm, post.Comments);
}
catch (Exception ex)
Expand Down
6 changes: 3 additions & 3 deletions BlogEngine/BlogEngine.Core/Data/CustomFieldRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public CustomField FindById(string type, string id, string key)
if (!Security.IsAuthorizedTo(Rights.AccessAdminPages))
throw new UnauthorizedAccessException();

var cf = Find("").Where(f => f.CustomType == type && f.ObjectId == id && f.Key == key).FirstOrDefault();
var cf = Find("").FirstOrDefault(f => f.CustomType == type && f.ObjectId == id && f.Key == key);
return cf;
}

Expand Down Expand Up @@ -157,10 +157,10 @@ public void ClearCustomFields(string type, string id)

bool AlreadyExists(CustomField item)
{
var field = CustomFieldsParser.CachedFields.Where(f => f.BlogId == item.BlogId
var field = CustomFieldsParser.CachedFields.FirstOrDefault(f => f.BlogId == item.BlogId
&& f.CustomType == item.CustomType
&& f.ObjectId == item.ObjectId
&& f.Key == item.Key).FirstOrDefault();
&& f.Key == item.Key);
return field != null;
}

Expand Down
4 changes: 2 additions & 2 deletions BlogEngine/BlogEngine.Core/Data/PageRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ static string GetUniqueSlug(string slug)

private static bool IsUniqueSlug(string slug)
{
return Page.Pages.Where(p => p.Slug != null && p.Slug.ToLower() == slug.ToLower())
.FirstOrDefault() == null ? true : false;
return Page.Pages
.FirstOrDefault(p => p.Slug != null && p.Slug.ToLower() == slug.ToLower()) == null ? true : false;
}

// if description not set, use first 100 chars in the post
Expand Down
8 changes: 4 additions & 4 deletions BlogEngine/BlogEngine.Core/Data/PostRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ static void UpdatePostCategories(Post post, List<CategoryItem> categories)
foreach (var cat in categories)
{
// add if category does not exist
var existingCat = Category.Categories.Where(c => c.Title == cat.Title).FirstOrDefault();
var existingCat = Category.Categories.FirstOrDefault(c => c.Title == cat.Title);
if (existingCat == null)
{
var repo = new CategoryRepository();
Expand Down Expand Up @@ -208,7 +208,7 @@ static List<TagItem> FilterTags(List<TagItem> tags)

foreach (var t in tags)
{
if (!uniqueTags.Any(u => u.TagName == t.TagName))
if (uniqueTags.All(u => u.TagName != t.TagName))
{
uniqueTags.Add(t);
}
Expand All @@ -233,8 +233,8 @@ static string GetUniqueSlug(string slug)

static bool IsUniqueSlug(string slug)
{
return Post.ApplicablePosts.Where(p => p.Slug != null && p.Slug.ToLower() == slug.ToLower())
.FirstOrDefault() == null ? true : false;
return Post.ApplicablePosts
.FirstOrDefault(p => p.Slug != null && p.Slug.ToLower() == slug.ToLower()) == null ? true : false;
}

// if description not set, use first 100 chars in the post
Expand Down
6 changes: 3 additions & 3 deletions BlogEngine/BlogEngine.Core/Data/RolesRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public RoleItem FindById(string id)
var roles = new List<Data.Models.RoleItem>();
roles.AddRange(System.Web.Security.Roles.GetAllRoles().Select(r => new Data.Models.RoleItem { RoleName = r, IsSystemRole = Security.IsSystemRole(r) }));

return roles.Where(r => r.RoleName.ToLower() == id.ToLower()).FirstOrDefault();
return roles.FirstOrDefault(r => r.RoleName.ToLower() == id.ToLower());
}

/// <summary>
Expand Down Expand Up @@ -101,7 +101,7 @@ public bool Update(RoleItem role, string oldRole)
if (!Security.IsAuthorizedTo(Rights.EditRoles))
throw new System.UnauthorizedAccessException();

var updateRole = System.Web.Security.Roles.GetAllRoles().Where(r => r.ToString() == oldRole).FirstOrDefault();
var updateRole = Roles.GetAllRoles().FirstOrDefault(r => r.ToString() == oldRole);

if (updateRole == null)
throw new ApplicationException("Role not found");
Expand Down Expand Up @@ -172,7 +172,7 @@ public IEnumerable<Group> GetRoleRights(string role)

var category = rightDetails == null ? RightCategory.General : rightDetails.Category;

var group = groups.Where(g => g.Title == category.ToString()).FirstOrDefault();
var group = groups.FirstOrDefault(g => g.Title == category.ToString());

var prm = new Permission();
var rt = Right.GetRightByName(right.ToString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,17 +117,17 @@ static string ReplaceCustomFields(string html)

if (s[1] == "POST")
{
var cf = postFields.Where(f => f.Key.ToLower() == key.ToLower()
&& f.ObjectId.ToLower() == id.ToLower()).FirstOrDefault();
var cf = postFields.FirstOrDefault(f => f.Key.ToLower() == key.ToLower()
&& f.ObjectId.ToLower() == id.ToLower());

if (cf != null)
val = cf.Value;
}

if (s[1] == "THEME")
{
var cf = themeFields.Where(f => f.Key.ToLower() == key.ToLower()
&& f.ObjectId.ToLower() == id.ToLower()).FirstOrDefault();
var cf = themeFields.FirstOrDefault(f => f.Key.ToLower() == key.ToLower()
&& f.ObjectId.ToLower() == id.ToLower());

if (cf != null)
val = cf.Value;
Expand Down
4 changes: 2 additions & 2 deletions BlogEngine/BlogEngine.Core/Data/Services/Json.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public static CommentItem GetComment(Comment c, List<Comment> postComments)
jc.Title = c.Teaser.Length < 80 ? c.Teaser : c.Teaser.Substring(0, 80) + "...";
jc.DateCreated = c.DateCreated.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
jc.RelativeLink = c.RelativeLink;
jc.HasChildren = postComments.Where(pc => pc.ParentId == c.Id).FirstOrDefault() != null;
jc.HasChildren = postComments.FirstOrDefault(pc => pc.ParentId == c.Id) != null;
jc.Avatar = Gravatar(c);
return jc;
}
Expand Down Expand Up @@ -223,7 +223,7 @@ static SelectOption ItemParent(Guid? id)
if (id == null || id == Guid.Empty)
return null;

var item = Category.Categories.Where(c => c.Id == id).FirstOrDefault();
var item = Category.Categories.FirstOrDefault(c => c.Id == id);
return new SelectOption { OptionName = item.Title, OptionValue = item.Id.ToString() };
}

Expand Down
14 changes: 7 additions & 7 deletions BlogEngine/BlogEngine.Core/Data/StatsRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ public Stats Get()
if (!Security.IsAuthorizedTo(Rights.EditOtherUsersPosts))
postList = postList.Where(p => p.Author.ToLower() == Security.CurrentUser.Identity.Name.ToLower()).ToList();

stats.PublishedPostsCount = postList.Where(p => p.IsPublished == true).Count();
stats.DraftPostsCount = postList.Where(p => p.IsPublished == false).Count();
stats.PublishedPostsCount = postList.Count(p => p.IsPublished == true);
stats.DraftPostsCount = postList.Count(p => p.IsPublished == false);

stats.PublishedPagesCount = Page.Pages.Where(p => p.IsPublished == true && p.IsDeleted == false).Count();
stats.DraftPagesCount = Page.Pages.Where(p => p.IsPublished == false && p.IsDeleted == false).Count();
stats.PublishedPagesCount = Page.Pages.Count(p => p.IsPublished == true && p.IsDeleted == false);
stats.DraftPagesCount = Page.Pages.Count(p => p.IsPublished == false && p.IsDeleted == false);

CountComments(stats);

Expand Down Expand Up @@ -70,9 +70,9 @@ void CountComments(Stats stats)
if (post.Author.ToLower() != Security.CurrentUser.Identity.Name.ToLower())
continue;

stats.PublishedCommentsCount += post.Comments.Where(c => c.IsPublished == true && c.IsDeleted == false).Count();
stats.UnapprovedCommentsCount += post.Comments.Where(c => c.IsPublished == false && c.IsSpam == false && c.IsDeleted == false).Count();
stats.SpamCommentsCount += post.Comments.Where(c => c.IsPublished == false && c.IsSpam == true && c.IsDeleted == false).Count();
stats.PublishedCommentsCount += post.Comments.Count(c => c.IsPublished == true && c.IsDeleted == false);
stats.UnapprovedCommentsCount += post.Comments.Count(c => c.IsPublished == false && c.IsSpam == false && c.IsDeleted == false);
stats.SpamCommentsCount += post.Comments.Count(c => c.IsPublished == false && c.IsSpam == true && c.IsDeleted == false);
}
}

Expand Down
8 changes: 4 additions & 4 deletions BlogEngine/BlogEngine.Core/Data/TrashRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,11 @@ public bool Restore(string trashType, Guid id)
}
break;
case "Post":
var delPost = Post.DeletedPosts.Where(p => p.Id == id).FirstOrDefault();
var delPost = Post.DeletedPosts.FirstOrDefault(p => p.Id == id);
if (delPost != null) delPost.Restore();
break;
case "Page":
var delPage = Page.DeletedPages.Where(pg => pg.Id == id).FirstOrDefault();
var delPage = Page.DeletedPages.FirstOrDefault(pg => pg.Id == id);
if (delPage != null) delPage.Restore();
break;
default:
Expand Down Expand Up @@ -189,11 +189,11 @@ public bool Purge(string trashType, Guid id)
}
break;
case "Post":
var delPost = Post.DeletedPosts.Where(p => p.Id == id).FirstOrDefault();
var delPost = Post.DeletedPosts.FirstOrDefault(p => p.Id == id);
if (delPost != null) delPost.Purge();
break;
case "Page":
var delPage = Page.DeletedPages.Where(pg => pg.Id == id).FirstOrDefault();
var delPage = Page.DeletedPages.FirstOrDefault(pg => pg.Id == id);
if (delPage != null) delPage.Purge();
break;
default:
Expand Down
12 changes: 6 additions & 6 deletions BlogEngine/BlogEngine.Core/Data/ViewModels/DashboardVM.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ private void LoadPosts()

foreach (var p in posts)
{
ApprovedCommentsCnt += p.Comments.Where(c => c.IsPublished && !c.IsDeleted).Count();
PendingCommentsCnt += p.Comments.Where(c => !c.IsPublished && !c.IsSpam && !c.IsDeleted).Count();
SpamCommentsCnt += p.Comments.Where(c => !c.IsPublished && c.IsSpam && !c.IsDeleted).Count();
ApprovedCommentsCnt += p.Comments.Count(c => c.IsPublished && !c.IsDeleted);
PendingCommentsCnt += p.Comments.Count(c => !c.IsPublished && !c.IsSpam && !c.IsDeleted);
SpamCommentsCnt += p.Comments.Count(c => !c.IsPublished && c.IsSpam && !c.IsDeleted);
_comments.AddRange(p.Comments);
}
}
Expand All @@ -146,7 +146,7 @@ private void LoadTrash()
{
var posts = Post.DeletedPosts;
_trash = new List<TrashItem>();
if (posts.Count() > 0)
if (posts.Any())
{
foreach (var p in posts)
{
Expand All @@ -162,7 +162,7 @@ private void LoadTrash()
}
}
var pages = Page.DeletedPages;
if (pages.Count() > 0)
if (pages.Any())
{
foreach (var page in pages)
{
Expand All @@ -187,7 +187,7 @@ private void LoadTrash()

comms.AddRange(p.DeletedComments);
}
if (comms.Count() > 0)
if (comms.Any())
{
foreach (var c in comms)
{
Expand Down
2 changes: 1 addition & 1 deletion BlogEngine/BlogEngine.Core/Helpers/BlogGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public static bool ValidateProperties(string blogName, string userName, string e
return false;
}

if (Blog.Blogs.Where(b => b.Name.ToLower() == blogName.ToLower()).FirstOrDefault() != null)
if (Blog.Blogs.FirstOrDefault(b => b.Name.ToLower() == blogName.ToLower()) != null)
{
message = "Blog with this name already exists; Please select different name.";
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -707,7 +707,7 @@ public override bool SetupNewBlog(Blog newBlog, string userName, string email, s
{
if (conn.HasConnection)
{
Blog existingBlog = Blog.Blogs.Where(b => b.Name == "Template").FirstOrDefault();
Blog existingBlog = Blog.Blogs.FirstOrDefault(b => b.Name == "Template");

if (existingBlog == null)
existingBlog = Blog.Blogs[0];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public override void DeleteDirectory(string VirtualPath)
public override bool DirectoryExists(string VirtualPath)
{
VirtualPath = VirtualPath.VirtualPathToDbPath();
return new FileSystem.FileStoreDb(this.connectionString).FileStoreDirectories.Where(x => x.FullPath.ToLower() == VirtualPath.ToLower() && x.BlogID == Blog.CurrentInstance.Id).Count() > 0;
return new FileSystem.FileStoreDb(this.connectionString).FileStoreDirectories.Any(x => x.FullPath.ToLower() == VirtualPath.ToLower() && x.BlogID == Blog.CurrentInstance.Id);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public override void SaveSettings(StringDictionary settings)
throw new ArgumentNullException("settings");
}

var filename = string.Format("{0}settings.xml", Folder);
var filename = $"{Folder}settings.xml";
var writerSettings = new XmlWriterSettings { Indent = true };

// ------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ static string PackageType(List<PackageFile> files)
/// <returns>Version number</returns>
public static string GetInstalledVersion(string pkgId)
{
var pkg = BlogService.InstalledFromGalleryPackages().Where(p => p.PackageId == pkgId).FirstOrDefault();
var pkg = BlogService.InstalledFromGalleryPackages().FirstOrDefault(p => p.PackageId == pkgId);
return pkg == null ? "" : pkg.Version;
}

Expand Down
4 changes: 2 additions & 2 deletions BlogEngine/BlogEngine.Core/Services/Packaging/Gallery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ public static void Load(List<Package> packages)
if (string.IsNullOrEmpty(jp.IconUrl))
jp.IconUrl = DefaultThumbnail("");

if (extras != null && extras.Count() > 0)
if (extras != null && extras.Any())
{
var extra = extras.Where(e => e.Id.ToLower() == pkg.Id.ToLower() + "." + pkg.Version).FirstOrDefault();
var extra = extras.FirstOrDefault(e => e.Id.ToLower() == pkg.Id.ToLower() + "." + pkg.Version);

if (extra != null)
{
Expand Down
2 changes: 1 addition & 1 deletion BlogEngine/BlogEngine.Core/Services/Security/Security.cs
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ public static bool IsAuthorizedTo(Rights right)
/// <returns></returns>
public static bool IsAuthorizedTo(AuthorizationCheck authCheck, IEnumerable<Rights> rights)
{
if (rights.Count() == 0)
if (!rights.Any())
{
// Always return false for this. If there's a mistake where authorization
// is being checked for on an empty collection, we don't want to return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ private void LoadBlogExtendedPosts(BlogMLBlog blog)
if (post.PostType == BlogPostTypes.Normal)
{
BlogMLPost p = post;
blogsExtended.Where(b => b.PostUrl == p.PostUrl).FirstOrDefault().BlogPost = post;
blogsExtended.FirstOrDefault(b => b.PostUrl == p.PostUrl).BlogPost = post;
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,17 +168,15 @@ public static ExtensionSettings GetSettings(string extensionName, string setting

if (!Blog.CurrentInstance.IsPrimary && extension.SubBlogEnabled)
{
return extension.Settings.Where(
setting => setting != null
return extension.Settings.FirstOrDefault(setting => setting != null
&& setting.Name == settingName
&& setting.BlogId == Blog.CurrentInstance.Id).FirstOrDefault();
&& setting.BlogId == Blog.CurrentInstance.Id);
}

var primId = Blog.Blogs.FirstOrDefault(b => b.IsPrimary).BlogId;
return extension.Settings.Where(
setting => setting != null
return extension.Settings.FirstOrDefault(setting => setting != null
&& setting.Name == settingName
&& (setting.BlogId == primId || setting.BlogId == null)).FirstOrDefault();
&& (setting.BlogId == primId || setting.BlogId == null));
}

/// <summary>
Expand Down
Loading

0 comments on commit 166a4ca

Please sign in to comment.