Reputation:
I have a list where I can get alot of objects.
List<string[]> registros
That I want to do is to get register 0 of each object, for example object 0
I want to get only "CORP" value and so on with all objects. So I try
foreach (var reg in registros[0])
{
var list = new[]
{
new { registros, Name = "Unidad" }
}.ToList();
var a = list;
}
But it only return one object with all register inside it. What am I doing wrong? How can I create list of first item of all objects?
Upvotes: 1
Views: 875
Reputation: 40726
How about using LINQ:
var s =
registros
.Select( r => r?.FirstOrDefault() )
.Where( r => r != null )
.ToList();
Line 3 iterates over all List
items and selects the first (if available) or null
otherwise.
Line 4 removes those that are null
.
Line 5 converts to a List
.
Here is a .NET Fiddle of the above code.
Responding to your comment below, here is how to rename items in the list, without selecting:
foreach ( var list in registros )
{
if ( list != null && list.Length > 0 )
{
list[0] = "Unidad";
}
}
And a .NET Fiddle for it.
Upvotes: 1
Reputation: 145
I propose to do it in this way using LINQ:
List<string[]> registros = GetRegistros();
var onlyFirstInEach = registros.SelectMany(x => x.Take(1)).ToList();
Upvotes: 1