2017-01-30 143 views
-6

我想获得Id,但我只有名称。 我的代码如下所示:lambda表达式

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#中是不能接受的。 我需要做什么?

+1

定义*不接受*。编译时出错?你有'使用System.Linq;'坐在上面? –

+0

你能提供什么社区? – ad1Dima

+0

'Where'返回一个集合,但'FirstOrDefault'需要一个'bool'。你可能想要使用'Any'而不是'Where',或者在'Where'后面链接'FirstOrDefault'。正是这取决于'community'和'comid'是什么。 – Abion47

回答

1

当你使用LINQ的尝试工作,以简化第一逻辑,并打破它的步骤。
因此,首先,你需要找到与社区名称,所有的元素Where语句将用它帮助:

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

现在commList我们得到了他们。其次,您需要使用Ids的新数组(IEnumerable):

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

那就是它。您的下一步首先记录一条记录:

rawId = rawIds.First(); 

现在您已经有原始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); 
+0

伙计们,当你打-1时,至少留下评论为什么。此代码工作100%,这是一个问题的答案。 – Sergio

+0

谢谢,它运作良好。 –

+0

这不是我,但我的猜测是,这个答案是一个代码转储,没有解释为了使它工作而改变了什么。 – Abion47

0

尝试:

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

感谢您的帮助,但我正在为'''我得到的错误是不能转换'int?'以'int',所以我删除了问号,它的工作。 –

+1

@Rikvola'?'用于检查'FirstOrDefault'是否返回null,如果'community'中的元素都不符合条件,则返回null。如果它返回null,那么这段代码将抛出一个没有'?'的异常。然而,对于'?',整行有可能返回null,这意味着'CommunityId'必须是Nullable int或'int?'。或者,可以使用三元运算符来检查该行是否返回null,如果是,则返回一个默认值,例如'-1'。 – Abion47