查找字符串中最长的单词 - c#

好的,所以我知道像这样的问题在这里已经问了很多,但是我似乎无法使解决方案起作用。
我正在尝试从文件中获取一个字符串,并在该字符串中找到最长的单词。
简单。

我认为问题在于我是在string[]还是char[]上调用我的方法,当前stringOfWords返回char[]

我试图然后按长度递减顺序并获取第一个值,但是在ArgumentNullException方法上得到一个OrderByDescending

任何输入非常感谢。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace TextExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            var fileText = File.ReadAllText(@"C:\Users\RichardsPC\Documents\TestText.txt");
            var stringOfWords = fileText.ToArray();

            Console.WriteLine("Text in file: " + fileText);
            Console.WriteLine("Words in text: " + fileText.Split(' ').Length);

            // This is where I am trying to solve the problem
            var finalValue = stringOfWords.OrderByDescending(n => n.length).First();

            Console.WriteLine("Largest word is: " + finalValue);
        }
    }
}

参考方案

在这种情况下,方法ToArray()返回char[],它是单个字符的数组。但是相反,您需要一个单独的单词数组。您可以这样获得:

string[] stringOfWords = fileText.Split(' ');

而且您的lambda表达式中有一个错字(大写L):

n => n.Length

C#无法将类型为“ System.Double”的对象转换为类型为“ System.Single” - c#

在判断此问题已得到回答之前,请阅读说明。我在下面有这个简单的代码:Dictionary<string, object> d = new Dictionary<string, object>(); d.Add("key" , 30d); System.Diagnostics.Debug.WriteLine($…

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

改造正在返回一个空的响应主体 - java

我正在尝试使用Retrofit和Gson解析一些JSON。但是,我得到的响应机构是空的。当我尝试从对象中打印信息时,出现NullPointerException。我确保URL正确,并且我也确保POJO也正确。我正在使用jsonschema2pojo来帮助创建POJO类。这是我要解析的JSON{ "?xml": { "@versi…

每个文件合并后添加换行 - python

我有很多类似以下内容的JSON文件:例如。1.json{"name": "one", "description": "testDescription...", "comment": ""} test.json{"name"…

System.out.printf不打印整数参数 - java

我是Java编程的新手,无法从另一个类返回方法。这两个类都可以编译并成功运行。我可以从一个类中调用一个简单的int,但是当我想计算用户输入的两个输入整数时,我只会得到一个空格。这是我的计算课class calculations { public final int AGE = 53; public int numbers(int num1, int num2…