使用linq查询时的行号

时间:2011-08-11 07:29:58

标签: c# asp.net linq .net-4.0

我使用流式阅读器读取文本文件,然后使用Linq检索信息

String fileContent = prodFileStreamReader.ReadToEnd();

 var mydata = from con in fileContent.Split('$').Select(x => x.Trim())
                    where !String.IsNullOrEmpty(con)
                    select new BaseSegment
                    {
                      dataID = con.Substring(0, con.IndexOf('#')),
                      dataElms = con.Split('#').ToArray(),
                      dataCon = con,
           lineNumber = 
                    };

我还想获得行号。我尝试使用索引,但我无法做到。如何查询获取索引并将其分配给lineNumber?

6 个答案:

答案 0 :(得分:7)

尝试使用select项目索引到每个项目中,如msdn文章中所述:http://msdn.microsoft.com/en-us/library/bb534869.aspx

在你的情况下这样的事情(未经测试):

var mydata = fileContent.Split('$')
             .Select(x => x.Trim())
             .Where(con => !String.IsNullOrEmpty(con))
             .Select((con, index) => new
                             {
                                 dataID = con.Substring(0, con.IndexOf('#')),
                                 dataElms = con.Split('#').ToArray(),
                                 dataCon = con,
                                 lineNumber = index
                             });

答案 1 :(得分:1)

对于初学者,我不会将文件作为一个大字符串读取。使用可以在小块中处理它的方法。例如,使用File.ReadLines()逐行读取文件。以这种方式获取行号会比一次读取所有行号更容易,只是为了再次将其拆分。

const string filePath = ...;
var myData =
    from pair in File.ReadLines(filePath)
                     .Select((LineNumber, Line) => new { LineNumber, Line })
    where ...
    select new BaseSegment
    {
        ...
        Line = pair.Line,
        LineNumber = pair.LineNumber,
    };

p.s。,你应该坚持通常的C#命名约定。您的类的公共属性应使用PascalCasing,而不是camelCasing,不应缩写。

用于处理内容的代码看起来很尴尬。如果我知道文件的样子,它可能会得到改善。我会把它留下来,直到你能告诉我们它是怎么回事。

答案 2 :(得分:0)

这个怎么样?

var animalList = from a in animals
                         select new { Animal = a, Index = animals.IndexOf(a) };

或在您的情况下......

Index = fileContent.IndexOf(con)

答案 3 :(得分:0)

如果整个数据都在myData中,那么你可以直接从myData使用索引。

答案 4 :(得分:0)

尝试一下:

String fileContent = prodFileStreamReader.ReadToEnd();

 var mydata = from con in fileContent.Split('$').Select(x => x.Trim())
                    where !String.IsNullOrEmpty(con)
                    select new BaseSegment
                    {
                      dataID = con.Substring(0, con.IndexOf('#')),
                      dataElms = con.Split('#').ToArray(),
                      dataCon = con,
           lineNumber = Array.IndexOf(fileContent.Split('$').Select(x => x.Trim(),con)
                    };

Array.IndexOf(yourArrey,the string you looking for); -> will return the index in the arrey.

答案 5 :(得分:-1)

你可以尝试这样的事情

long index = 0;
var xElementsAndNodes = from xmlElement in elementsColl
select new
{
  Index = index += 1,
  ....
}