代码之家  ›  专栏  ›  技术社区  ›  jay_t55

不相配

  •  2
  • jay_t55  · 技术社区  · 16 年前

    也许是我做错了什么。我只是在学习Linq,因为我很无聊。到目前为止还不错。我制作了一个小程序,它基本上只是将所有匹配项(foreach)输出到一个label控件中。

    代码:

    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();
            }
        }
    }
    

    除了一件事之外,我上面所说的一切都很完美。我检查了一个文件,其中包含以下文本:

    文件:


    杰森

    这个
    滑稽的


    这个
    世界
    杰森
    杰森

    佩齐门蒂

    我猜如果同一个匹配中有多个匹配,它不会返回匹配?

    我这样说对吗?这就是它的本意吗?你会建议我如何让它总是返回一个匹配,无论有多少相同的匹配。我的意思是,根据上面的代码,我会认为它会返回以下输出。。。当我在文本框1中键入“jason”时,这不是foreach(查询中的项)的作用吗


    杰森
    杰森

    2 回复  |  直到 14 年前
        1
  •  1
  •   Thomas Levesque    16 年前

    你可能在这行的末尾有一个空格。。。试试这个:

                IEnumerable<String> Query =
                    from instance in Content
                    where instance.Trim() == Value.Trim()
                    orderby instance
                    select instance;
    
        2
  •  1
  •   David Wengier    16 年前

    正如Thomas Levesque所说,可能是文件末尾有空格,但也可能是文件没有file.ReadAllLines()所期望的行尾。它需要CRLF结尾,因此,例如,如果您只有LF结尾,您可能会认为该方法只返回一个“行”。

    推荐文章