Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve the first item from a list

Tags:

arrays

c#

list

I'm having trouble getting the first item from a list. The data is added to the list from a text file however, the system is returning System.Linq.Enumerable+<TakeIterator>d__25'1[System.String] instead of the first item in the list.

The following is my implementation

string[] inputData = rawInputData.Split(',');
List<string> splitData = new List<string>(inputData.Length);
splitData.AddRange(inputData);
var numberOfCaves = splitData.Take(1);
Console.Write(numberOfCaves);

I am unsure as why this is happening and any suggestions would be appreciated, Thanks!

like image 741
bdg Avatar asked Nov 21 '18 21:11

bdg


1 Answers

Just use FirstOrDefault.

You can also save yourself a lot of footwork, as Split returns an array (IEnumerable) already. So you don't have to create a new list and add it

The problem is essentially, Take Returns an IEnumerable (a list for all intents and purposes, that hasn't been traversed yet), Console.WriteLine doesn't know how to convert it to a string implicitly so it writes its type name

var result = rawInputData.Split(',').FirstOrDefault();

if(result == null) // checks if there are no elements and results null
  Console.WriteLine("darn");
else    
  Console.WriteLine(result);

Additional Resources

Enumerable.FirstOrDefault Method

Returns the first element of a sequence, or a default value if no element is found.

String.Split Method

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

Enumerable.Take(IEnumerable, Int32) Method

Returns a specified number of contiguous elements from the start of a sequence.

  • Returns IEnumerable<TSource> An IEnumerable that contains the specified number of elements from the start of the input sequence.

Enumerable Class

  • The methods in this class provide an implementation of the standard query operators for querying data sources that implement IEnumerable. The standard query operators are general purpose methods that follow the LINQ pattern and enable you to express traversal, filter, and projection operations over data in any .NET-based programming language.

  • The majority of the methods in this class are defined as extension methods that extend IEnumerable. This means they can be called like an instance method on any object that implements IEnumerable.

  • Methods that are used in a query that returns a sequence of values do not consume the target data until the query object is enumerated. This is known as deferred execution. Methods that are used in a query that returns a singleton value execute and consume the target data immediately.

Update

As a side note, result can never be null here. – Antonín Lejsek

Which is indeed correct

string.Split Will return at least 1 element

like image 57
TheGeneral Avatar answered Oct 31 '22 18:10

TheGeneral