嘿所有我找到了以下代码HERE,并且想知道如果我还可以通过LINQ查询或其他方式获取单词出现的行号,是否可行?
<div class="page-wrap">
<div class="form">
<h1>Join Now</h1>
<?php
echo $this->Form->create(null, ['controller' => 'users', 'action' => 'addMultiple']);
echo $this->Form->input('1.full_name');
echo $this->Form->input('1.username');
echo $this->Form->input('1.email');
echo $this->Form->input('1.password');
echo $this->Form->input('1.password_confirmation', array('type' => 'password'));
if ($current_user['role'] === 1 && isset($logged_in)) {
echo $this->Form->input('1.role', ['type' => 'select', 'options' => ['1' => 'Admin', '2' => 'Editor', '3' => 'Author', '4' => 'Reader'], 'default' => '4']);
}
echo $this->Form->input('2.full_name');
echo $this->Form->input('2.username');
echo $this->Form->input('2.email');
echo $this->Form->input('2.password');
echo $this->Form->input('2.password_confirmation', array('type' => 'password'));
if ($current_user['role'] === 1 && isset($logged_in)) {
echo $this->Form->input('2.role', ['type' => 'select', 'options' => ['1' => 'Admin', '2' => 'Editor', '3' => 'Author', '4' => 'Reader'], 'default' => '4']);
}
echo $this->Form->button(__('Sign Up'));
echo $this->Form->end();
?>
</div>
</div>
该代码适用于查找单词但我真的希望能够知道它在哪个行上找到。
任何帮助都会很棒!
答案 0 :(得分:2)
传递项目索引的LINQ Select
方法has a overload。
Dim startFolder = "C:\Users\me\Documents\Visual Studio 2012\Projects\project"
Dim matches =
From f In Directory.EnumerateFiles(startFolder, "*.vb", SearchOption.AllDirectories)
From l In File.ReadLines(f).Select(Function(x, i) New With { .Line = x, .LineNo = i + 1})
Where l.Line.Contains(word2Search)
Select FileName = f, LineNo = l.LineNo, Line = l.Line
匹配将是具有IEnumerable
,FileName
和LineNo
属性的Line
个对象。
<强>更新强>
要获取文件名和匹配行索引的数组,您可以执行以下操作:
Dim matches =
From f In Directory.EnumerateFiles(startFolder, "*.vb", SearchOption.AllDirectories)
From l In File.ReadLines(f).Select(Function(x, i) New With { .Line = x, .LineNo = i + 1})
Where l.Line.Contains(word2Search)
Select File = f, LineNo = l.LineNo
Group By File Into g = Group
Select FileName = File, LineNos = g.Select(Function(x) x.LineNo).ToArray()
这将为您提供IEnumerable
具有FileName
和LineNos
属性的对象。
在行中查找匹配项的位置需要进行一些更改,因为Contains
只返回Boolean
。您可以使用Regex.Matches
查找该行中匹配的位置,所以:
Dim matches =
From f In Directory.EnumerateFiles(startFolder, "*.vb", SearchOption.AllDirectories)
From l In File.ReadLines(f).Select(Function(x, i) New With { .Line = x, .LineNo = i + 1})
Where l.Line.Contains(word2Search)
Select File = f, LineNo = l.LineNo,
MatchPositions = Regex.Matches(l.Line, Regex.Escape(word2Search)).Cast(Of Match)().Select(Function(x) x.Index)
Group By File Into g = Group
Select FileName = File, Matched = g.Select(Function(x) New With { x.LineNo, .Positions = x.MatchPositions.ToArray() }).ToArray()
在此之后,您最终得到IEnumerable
个具有FileName
和Matched
属性的对象(遗憾的是,VB.NET不会被称为Matches
因为它与matches
变量冲突,但你可以根据自己的喜好来玩它。 Matched
属性是具有LineNo
和Positions
属性的对象数组,Positions
是字符串中索引的数组(基于零,因此添加{{1} 1}}如果你喜欢,那就在那里。