Get first item in list from linq query

前端 未结 3 1524
清酒与你
清酒与你 2020-12-10 16:58

I wish to get just the very first record I realize the the \"Take() will not work.

So I have a List that queries another list

List etch         


        
相关标签:
3条回答
  • 2020-12-10 17:18

    Use the FistOrDefault method to safely return the first item from your query, or null if the query returned no results:

    var result =
        (from vio in AddPlas
         where etchList.Any(vioID => vio.Key.Formatted.Equals(vioID))
         select new
         {
            EtchVectors = vio.Shapes.FistOrDefault()
         })
    

    Or equivalently:

    var result = AddPlas.Where(x => etchList.Any(y => x.Key.Formatted.Equals(y)))
                        .Select(x => new { EtchVectors = x.Shapes.FistOrDefault() });
    
    0 讨论(0)
  • 2020-12-10 17:37

    I don't suppose it's as easy as First()?

    If you expect that your query will not return any results, use FirstOrDefault()

    Update

    If what you are asking for is "Get the first Shapes from each AddPla", then add the First to your select statement, rather than at the end

    select new { EtchVectors = vio.Shapes.First() }
    
    0 讨论(0)
  • 2020-12-10 17:38

    You can try with FirstOrDefault.

    var query = (from vio in AddPlas
                where etchList.Any(vioID => vio.Key.Formatted.Equals(vioID))
                select new
                {
                    EtchVectors = vio.Shapes
                }).FirstOrDefault();
    
    0 讨论(0)
提交回复
热议问题