gpt4 book ai didi

c# - 遍历 ICollection 返回一个 bool

转载 作者:行者123 更新时间:2023-11-30 14:45:53 25 4
gpt4 key购买 nike

我实际上是在创建一个博客(命名约定略有不同)。我的“post”类(我称之为故事)有一个属性,它与一个名为“visibility”的表相关联。帖子可以是公开的也可以是私有(private)的。

当用户查看另一个成员的个人资料时,他们应该能够看到所有公开的帖子。

我已经创建了一个 View 模型:

public class UserDetailsViewModel
{
public bool IsRegisteredUser { get; set; }
//public bool IsStoryPrivate { get; set; }
public int StoryCount { get; set; }
public int ReviewCount { get; set; }
public ApplicationUser User { get; set; }
public virtual IEnumerable<Story> Stories { get; set; }
}

在我的用户 Controller 中,当有人点击个人资料查看个人资料的详细信息时,我从数据库中获取用户,获取与该用户关联的所有故事(帖​​子)并包括与帖子相关的各种表格,获取帖子数量,并将这些值插入我的 View 模型。这是用这段代码完成的:

public ActionResult Details(string id)
{
//verify an id was passed
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

//if an id was given as a parameter, find the user associated with that id
var foundUser = dbContext.Users.SingleOrDefault(x => x.Id == id);

//verify a user was found
if (foundUser == null)
{
return HttpNotFound();
}

var isRegisteredUser = IsRegisteredUser(foundUser);

//if a user was found, get all stories associated with the foundUser
var stories = dbContext.Stories
.Include("Genre")
.Include("StoryType")
.Include("StoryAgeRange")
.Include("Visibility")
.Where(x => x.AuthorId == foundUser.Id);

var reviews = dbContext.Reviews.Where(x => x.ReviewerId == foundUser.Id);

int numOfStories = stories.Count();
int numOfReviews = reviews.Count();

//create the viewmodel
var viewModel = new UserDetailsViewModel
{
User = foundUser,
//IsStoryPrivate = isStoryPrivate,
IsRegisteredUser = isRegisteredUser,
Stories = stories,
StoryCount = numOfStories,
ReviewCount = numOfReviews
};

return View(viewModel);
}

我想做的是创建一个名为 IsStoryPrivate 的方法,它返回一个 bool 值并且需要遍历故事中的每个故事。然后将 true/false 值传递给 IsStoryPrivate 字段中的 viewModel。

我试过这段代码:

public bool IsStoryPrivate(Story story)
{
return story.Visibility.Name == "Private";
}

然后尝试在 Controller 中调用它但失败了,因为我没有将单个故事对象传递给该方法,而是传递了一个集合 - 或者故事列表。

然后我试了一下:

public bool IsStoryPrivate(ICollection<Story> story)
{
foreach (story in story)
{
return Story.Visibility.Name == "Private";
}
}

这也会导致错误。我不确定如何编写代码来遍历从数据库返回的故事列表,并为我可以发送到 View 模型的每个故事提供 true/false。

最佳答案

不是从数据库中获取所有故事然后决定是否显示它们,而是对初始查询进行过滤:

var stories = dbContext.Stories
.Include("Genre")
.Include("StoryType")
.Include("StoryAgeRange")
.Include("Visibility")
.Where(x => x.AuthorId == foundUser.Id);

// filter for public stories only when the author is not the current user
if (!isRegisteredUser)
{
stories = stories.Where(x => x.Visibility.Name == "Public");
}

如果您正在为检查加载 Visibilty 关系,您现在可以省略它:

var stories = dbContext.Stories
.Include("Genre")
.Include("StoryType")
.Include("StoryAgeRange")
.Where(x => x.AuthorId == foundUser.Id);

关于c# - 遍历 ICollection 返回一个 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51619260/

25 4 0