making a list using inner query in Linq in C#

二次信任 提交于 2021-02-05 11:26:47

问题


I am trying to create a sublist using Linq but don't understand the error in this. I don't think i am doing wrong but i think others eye will help me to sort this issue.

var dataList = File.ReadAllLines(inputFile);
 dataList = from line in dataList
              let temp = from data in line.Split(';').ToList()
                         where line.Split(';').ToList().IndexOf(data) != 0 ||line.Split(';').ToList().IndexOf(data) != 1
                          select data
                          select string.Join(",",temp);

I am getting error saying that IEnumerable list cannot be implicitly converted to string[]..:(


回答1:


dataList is an array, while LINQ returns IEnumerable<string>. Add ToArray to the end of the query:

dataList = (from line in dataList
            let temp = from data in line.Split(';').ToList()
                        where line.Split(';').ToList().IndexOf(data) != 0 || line.Split(';').ToList().IndexOf(data) != 1
                        select data
            select string.Join(",", temp)).ToArray();



回答2:


When I tried to compile that code you posted I get the following exception:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string[]'. An explicit conversion exists (are you missing a cast?)

Reason is that you are trying to reuse dataList, but the return types of File.ReadAllLines and string.Join methods don't match. This fixes it:

dataList = (from line in dataList
                   let temp = from data in line.Split(';').ToList()
                              where line.Split(';').ToList().IndexOf(data) != 0 || line.Split(';').ToList().IndexOf(data) != 1
                              select data
                   select string.Join(",", temp)).ToArray();

Cheers,




回答3:


What version of the .NET Framework are you on? The overload of String.Join that takes an IEnumerable<string> was only introduced in v4.0. If you're on an earlier version it's trying to take that IEnumerable<string> and use it as a string[].

Also (this doesn't fix your problem) I think the || in the 4th line should be a &&.



来源:https://stackoverflow.com/questions/15805210/making-a-list-using-inner-query-in-linq-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!