Search code examples
c#linqlambdawhere-clause

Lambda where Expression


I want to get the Id, but i only have the Name. My code looks like this:

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

Comments is a 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; }
}

Community as well:

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

But the statement where isn't existing in this scenario in C#.


Solution

  • When you work with linq try to simplify logic first, and break it on steps.
    So first, you need to find all elements with CommunityName, Where statement will help with it:

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

    Now in commList we got them. Second you need new array (IEnumerable) with Ids:

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

    Thats it. Your next step is taking one record, first:

    rawId = rawIds.First();
    

    Now you have raw id, raw because it could be null. You need to check it for Null:

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

    The record above could be simplify:

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

    And now just join all linqs step by step:

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