Get first item in list from linq query

I want to get only the very first record, which I understand that "Take () will not work.

So I have a list that requests another list

List<string> etchList = new List<string>(); etchList.Add("709"); 

Linq request

 var query = (from vio in AddPlas where etchList.Any(vioID => vio.Key.Formatted.Equals(vioID)) select new { EtchVectors = vio.Shapes }).ToList().Take(1); 

Now this β€œTake (1)” will only work if I have other data in etchList, so this is not what I am looking for. The results that I get are as follows:

formatted
"clinesegs" 1013.98 5142.96 "LYR3_SIG2"
"clinesegs" 1020.16 5168.33 "LYR3_SIG2"
"clinesegs" 967.03 5151.31 "LYR3_SIG2"
"clinesegs" 971.43 5174.01 "LYR3_SIG2"

I want to ONLY return the first "line in the list

 "clinesegs" 1013.98 5142.96 "LYR3_SIG2" 

EDIT:

Ok, this code exists:

 public class AddPla { public AddPla() { Shapes = new List<Parse>(); } public Parse Key { get; set; } public Parse Pla { get; set; } public Parse Angle { get; set; } public Parse Default { get; set; } public List<Parse> Shapes { get; set; } public Parse DoubleBrace { get; set; } public Parse Number1 { get; set; } public Parse Number2 { get; set; } } public class Parse { public string Formatted { get; set; } public string Original { get; set; } } 

Then this list

  var AddPlas = new List<AddPla>(); 
+6
source share
3 answers

I don’t think it is as simple as First() ?

If you expect your query to return no results, use FirstOrDefault()

Update

If you ask "Get the first Shapes from each AddPla ", add First to your select statement, not the end

 select new { EtchVectors = vio.Shapes.First() } 
+11
source

You can try it with FirstOrDefault .

 var query = (from vio in AddPlas where etchList.Any(vioID => vio.Key.Formatted.Equals(vioID)) select new { EtchVectors = vio.Shapes }).FirstOrDefault(); 
+5
source

Use the FistOrDefault method to safely return the first element 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
source

Source: https://habr.com/ru/post/944583/


All Articles