Lambda where 表达式

Lambda where Expression

我想获取Id,但我只有Name。 我的代码如下所示:

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

评论是class:

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; }
}

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

当您使用 linq 时,首先尝试简化逻辑,然后逐步分解。
所以首先,您需要找到所有带有 CommunityName 的元素,Where 语句将有助于它:

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

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

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

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

rawId = rawIds.First();

现在您有了原始 ID,原始 ID 可能为空。您需要检查它是否为空:

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

上面的记录可以简化:

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

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

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

尝试:

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