【问题标题】:Lambda where Expression [closed]Lambda where 表达式 [关闭]
【发布时间】:2017-01-30 11:08:32
【问题描述】:

我想获取 ID,但我只有名称。 我的代码如下所示:

var comments = new List<Comments>
        {
            new Comments{
                CommunityId = community.FirstOrDefault(comid => comid.IdCommunity.Where(comid.CommunityName == "TestCommunity")),
            }
        };

评论是一个类:

public class Comments
{
    public int IdComment { get; set; }
    public DateTime Timestamp { get; set; }
    public string Text { get; set; }
    public int UserId { get; set; }
    public int CommunityId { get; set; }
}

社区也是如此:

public class Community
{
    public int IdCommunity { get; set; }
    public string CommunityName { get; set; }
    public Pictures Picture { get; set; }
}

但是 where 在 C# 中不被接受。 我需要做什么?

【问题讨论】:

  • 定义不被接受。编译时出错?你有using System.Linq; 坐在上面吗?
  • 你能提供,什么是社区?
  • Where 返回一个集合,但 FirstOrDefault 需要一个 bool。您可能希望使用Any 而不是Where 或链接FirstOrDefault Where 之后。具体取决于communitycomid 是什么。
  • @PatrickHofman 是的,我已经使用 SystemLinq 进行了定义
  • @Abion47 好吧,我的错,我会更新我的问题。

标签: c# linq lambda where


【解决方案1】:

当您使用 linq 时,请先尝试简化逻辑,然后按步骤分解。
所以首先,你需要找到所有带有 CommunityName 的元素,Where 语句会有所帮助:

var commList = community.Where(com => com.CommunityName == "TestCommunity");

现在在 commList 中我们得到了它们。其次,您需要带有 ID 的新数组(IEnumerable):

rawIds = commList.Select(x=>x.IdCommunity);

就是这样。您的下一步是首先记录一条记录:

rawId = rawIds.First();

现在你有了 raw id,raw 因为它可能是 null。您需要检查它是否为 Null:

int Id;
if(rawId==null)
    Id = -1;
else
    Id = Convert.ToInt32(rawId);

上面的记录可以简化:

int Id = rawId == null? -1 : Convert.ToInt32(rawId);

现在只需逐步加入所有 linq:

rawId = community.Where(com => com.CommunityName == "TestCommunity").Select(com => com.IdCommunity).First();
int id = rawId == null ? -1 : Convert.ToInt32(rawId);

【讨论】:

  • 伙计们,当你点击-1时,至少留下评论为什么。此代码 100% 有效,它是一个问题的答案。
  • 谢谢,效果很好。
  • 不是我,但我猜这个答案是一个代码转储,没有解释你为了让它工作而做了什么。
【解决方案2】:

尝试:

var comments = new List<Comments>
        {
            new Comments{
                CommunityId = community.FirstOrDefault(comid => comid.CommunityName == "TestCommunity")?.IdCommunity, //CommunityId should be nullable
            }
        };

【讨论】:

  • 感谢您的帮助,但我正在努力解决“?”我得到的错误是无法转换'int?到“int”,所以我删除了问号,它起作用了。
  • @Rikvola ? 用于检查FirstOrDefault 是否返回null,如果community 中的任何元素都不匹配条件,它将返回null。如果它确实返回 null,那么此代码将抛出没有 ? 的异常。但是,对于?,整行都有可能返回 null,这意味着 CommunityId 必须是 Nullable int 或 int?。或者,您可以使用三元运算符来检查该行是否返回 null,如果是,则让它返回一个默认值,例如 -1
猜你喜欢
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多