c# - FirstOrDefault() 方法是处理这种情况的好方法吗

标签 c# entity-framework entity-framework-4.1

<分区>

我有一个 Group 类,其中包含作为组成员的用户列表。
我使用 FirstOrDefault() 方法检查打开组页面的用户是否已经在该组中。
基于此,我显示“加入群组”或“离开群组”按钮。
我只是想知道对于这种情况,这是一种好的方法还是有更好的方法?

public class Group
{
    public virtual ICollection<UserInGroup> UsersInGroups { get; set; }
    ...
}

详细操作方法我首先加载组然后检查组中的用户:

public ActionResult Show(int groupId, string title)
{
    GroupViewModel groupiewModel = new GroupViewModel();

    var model = groupsRepository.GetGroupById(groupId);

    groupiewModel.Group = model;

    Guid userId = (Guid)Membership.GetUser().ProviderUserKey;
    var alreadyInGroup = model.UsersInGroups.FirstOrDefault(x => x.UserId == userId);

    if (alreadyInGroup != null)
        groupiewModel.IsInThisGroup = true;
    ...
}

最佳答案

我认为 Any 是更好的选择

bool alreadyInGroup = model.UsersInGroups.Any(x => x.UserId == userId); 

if (alreadyInGroup)
{
     ....

关于c# - FirstOrDefault() 方法是处理这种情况的好方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12289274/

相关文章:

c# - 编写谓词以使用 Entity Framework 搜索存储库时出现问题(相当于在 SQL 中使用 Join)

c# - 如何将连接字符串注入(inject) IDbContextFactory<T> 的实例?

c# - EF4.1(代码优先)——如何指定复合关系

entity-framework-4 - 如何在 Entity Framework 中配置事务?

c# - 使用 TweetSharp 返回最近的 n 条推文

c# - 小数?在 Entity Framework 中

c# - Web API 重定向到网页

c# - 为什么有些文本框不接受 Control + A 快捷方式来默认全选

sql-server - 如何让 Entity Framework 1.0 在访问特定实体时使用 nolock 提示

c# - Entity Framework 4.1 - EFTracingProvider