gpt4 book ai didi

c# - 从列表中检索第一项

转载 作者:行者123 更新时间:2023-11-30 13:35:30 24 4
gpt4 key购买 nike

我无法从列表中获取第一项。数据从文本文件添加到列表中,但是系统返回 System.Linq.Enumerable+<TakeIterator>d__25'1[System.String]而不是列表中的第一项。

下面是我的实现

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

我不确定为什么会这样,如有任何建议,我们将不胜感激,谢谢!

最佳答案

只需使用 FirstOrDefault .

您还可以节省很多步法,如Split已经返回一个数组 ( IEnumerable )。因此您不必创建新列表并添加它

问题本质上是,Take返回 IEnumerable (所有意图和目的的列表,尚未遍历),Console.WriteLine不知道如何将其转换为 string隐式地写它的类型名

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

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

其他资源

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.

更新

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

这确实是正确的

string.Split将返回至少 1 个元素

关于c# - 从列表中检索第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53420681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com