也许这是我做错了。我只是在学习Linq因为我很无聊。到目前为止一切顺利。我制作了一个小程序,它基本上只是将所有匹配(foreach)输出到标签控件中。
用法:在文本框中输入文本,单击按钮。程序允许您选择与文本框值匹配的文件,并返回标签控件中的匹配项。
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace LinqTests
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected internal String[]
Content;
public String
Value;
private void button1_Click(object sender, EventArgs e)
{
Value = textBox1.Text;
OpenFileDialog ofile = new OpenFileDialog();
ofile.Title = "Open File";
ofile.Filter = "All Files (*.*)|*.*";
if (ofile.ShowDialog() == DialogResult.OK)
{
Content =
File.ReadAllLines(ofile.FileName);
IEnumerable<String> Query =
from instance in Content
where instance == Value
orderby instance
select instance;
foreach (String Item in Query)
label1.Text +=
Item + Environment.NewLine;
}
else Application.DoEvents();
ofile.Dispose();
}
}
}
问题 除了一件事,我上面所做的工作完美无缺。我有一个我检查的文件,其中包含以下文本:
文件:
<小时/> 杰森
......它永远不会回归“杰森”。但它总会返回任何其他词。
如果有更多相同的匹配,我猜它不会返回匹配?
这样说我是否正确?它应该是这样的吗?如果有多少相同的比赛,你会如何建议我总是返回一场比赛。我的意思是我会认为它将返回以下输出,基于上面的代码...不是foreach(查询中的项目)是什么?,当我在textBox1中键入“jason”时:
杰森
杰森
杰森
杰森
..但它没有返回任何原因:(
答案 0 :(得分:1)
你可能在行尾有一个空白...试试这个:
IEnumerable<String> Query =
from instance in Content
where instance.Trim() == Value.Trim()
orderby instance
select instance;
答案 1 :(得分:1)
您对预期发生的事情是正确的,也就是说,您会在文本文件中的每个单词实例中显示一行。
可能是你的文件末尾有空格,正如Thomas Levesque所说,但也可能是你的文件没有File.ReadAllLines()所期望的行结尾。它期望CRLF结尾,所以如果你只有LF结尾,你可能会觉得该方法只返回一个“行”。