我想获得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; }
}
但C#中不接受的地方。 我需要做什么?
答案 0 :(得分:2)
当您使用linq时,首先尝试简化逻辑,然后在步骤中将其分解 首先,您需要使用CommunityName找到所有元素,Where语句将帮助它:
var commList = community.Where(com => com.CommunityName == "TestCommunity");
现在在commList中我们得到了它们。其次你需要新的数组(IEnumerable)和Ids:
rawIds = commList.Select(x=>x.IdCommunity);
多数民众赞成。您的下一步是首先记录一条记录:
rawId = rawIds.First();
现在你有原始id,raw,因为它可能为null。你需要检查Null:
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);
答案 1 :(得分:0)
尝试:
var comments = new List<Comments>
{
new Comments{
CommunityId = community.FirstOrDefault(comid => comid.CommunityName == "TestCommunity")?.IdCommunity, //CommunityId should be nullable
}
};