如何在txt文件C#中搜索数字? [英] How to search for numbers in txt file C# ?

查看:86
本文介绍了如何在txt文件C#中搜索数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何打开.txt文件并将输入或空格分隔的数字读入数组列表?

示例图像: http://i.stack.imgur.com/hZaE2.png

现在我要做的是搜索(for 1 2 9)并发送到控制台。



我尝试了很多代码,但似乎没有任何工作:(



这是我目前的代码:

 使用系统; 
< span class =code-keyword>使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
using System.IO;
namespace Padroes
{
计划
{
静态 void Main( string [] args)
{
try
{


// 使用流阅读器打开文本文件。
const string FILENAME = @ Example.txt;


列表< List< int>> data = new List< List< int>>();

string inputLine = ;
StreamReader reader = new StreamReader(FILENAME);

while ((inputLine = reader.ReadLine())!= null
{
inputLine = inputLine.Trim();
if (inputLine.Length > 0
{
List< int> inputArray = inputLine.Split( new char [] {' '},StringSplitOptions.RemoveEmptyEntries).Select(x = > INT .Parse(X))ToList();

data.Add(inputArray);
Console.WriteLine(inputLine);
}
}
}

catch (例外e)
{
Console.WriteLine( 无法读取文件:);
Console.WriteLine(e.Message);
}

Console.ReadKey();
}
}
}



这段代码这是我的输出: http://i.stack.imgur.com/5VdxN.png

现在我该怎么做才能搜索for(1 2 9)并仅将1 2 9发送到控制台?

解决方案

此回复假设您已成功将数据读入列表< List< int>> 名为'数据'

 私人列表< List< int>> data =  new 列表< List< int>> 
{
new 列表< int> { 1 2 3 }, new List< int> { 1 2 9 }, new 列表< int> { 4 3 ,< span class =code-digit> 2 }
};

// 注意返回值是可以为空的
< span class =code-keyword> private int ? findTuplet( params int [] ints)
{

< b> // begin edit 1

// 因为每列值的变化频率
// 是:column2 => column1 => column0
// 搜索可能会因更改而加速按比较顺序
// 以粗体显示

// 这将在找到第一个匹配时停止
< span class =code-comment> // var match = data.FirstOrDefault(lst =>
// lst [2] == ints [2]&& lst [1] == ints [1]&& ; lst [0] == ints [0]
// );


// 或...使用复合Where语句
// 但是,此处可能有更多评估
var match = data
.Where(dat = > dat [ 2 ] == ints [ 2 ])
.Where(dat = > dat [ 1 ] == ints [ 1 ])
。其中(dat = > dat [ 0 ] ==整数[ 0 ])

.FirstOrDefault();

// 结束编辑1


if (match == null return null ;

return data.IndexOf(match);
}

// 样本使用:
/ *
int? isMatch = findTuplet(4,13,2);

if(isMatch!= null)Console.WriteLine(Match {0} {1},(isMatch == null?not found:found at index:),(isMatch != null?isMatch.ToString():));


许多可能的方法之一是使用Linq [ ^ ]。



我建议创建自定义类如下:

  public   class  MyData 
{
private int x = 0 ;
private int y = 0 ;
private int z = 0 ;

public MyData( int _x, int _y, int _z)
{
x = _x;
y = _y;
z = _z;
}

public int X
{
get { return x; }
set {x = value ; }
}

public int Y
{
get { return y; }
set {y = value ; }
}

public int Z
{
get { return z; }
set {z = value ; }
}
}





用法:

  //  读取所有行 
string [] lines = File.ReadAllLines( @ D:\ Example.txt );

// 将数据查询到MyData类列表中
< span class =code-comment> // 拆分数据
列表< MyData> md =行
。选择(a = > new MyData(Convert.ToInt32(a .Split(' ')[ 0 ]),
Convert.ToInt32(a.Split(' ')[ 1 ]),
Convert.ToInt32(a.Split(' ')[ 2 ])))。ToList();

// 过滤数据
var result = md.Where(item => item.X == 1 && item.Y == 2 && item.Z == 9 );

// 在控制台中显示
foreach var 数据 结果)
{
Console.WriteLine( {0} {1} {2},data.X ,data.Y,data.Z);
}







如果你想要使用 Equals 方法比较数据,你必须实施Equals方法 [ ^ ]:



 < span class =code-comment> //  在课程定义的最后添加这段代码,就在最后}括号 
之前 public 覆盖 bool 等于(对象 otherData)
{
if (otherData == null return false ;

return this ==(MyData)otherData;
}

public static bool 运算符 ==(MyData md1,MyData md2)
{
返回 md1.X == md2.X&& md1.Y == md2.Y&& md1.Z == md2.Z;
}

public static bool operator !=(MyData md1,MyData md2)
{
return !(md1 == md2);
}





用法:

  //  创建 o 对象 -   MyData 的类型,将其用于比较 
MyData o = new MyData( 1 2 9 );
// 稍后
var 结果= md.Where(item => item.Equals(o));







[/编辑]



祝你好运!


试一试......可能会对你有所帮助



static void Main(string [] args)

{



string [] lines;

lines = System.IO.File.ReadAllLines(@D:\ Example.txt);



for(int k = 0; k< lines.length; k ++)>

{

if(lines [k] ==1 2 9)//把你的输入放在这里。

{

Console.WriteLine(lines [k] .ToString());

Console.ReadLine();

}

}



}

How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Example image:http://i.stack.imgur.com/hZaE2.png
Now what I want to do is to search (for 1 2 9 ) and send to the console.

I have tried a lot of code but nothing seems to work :(

This is my current code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Padroes
{
class Program
{
    static void Main(string[] args)
    {
        try
        {


            // Open the text file using a stream reader.
            const string FILENAME = @"Example.txt";


                List<List<int>> data = new List<List<int>>();

                string inputLine = "";
                StreamReader reader = new StreamReader(FILENAME);

                while ((inputLine = reader.ReadLine()) != null)
                {
                    inputLine = inputLine.Trim();
                    if (inputLine.Length > 0)
                    {
                        List<int> inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToList();

                        data.Add(inputArray);
                    Console.WriteLine(inputLine);
                    }
                }
            }

        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }

        Console.ReadKey();
    }
}
}


Whith this code this is my output:http://i.stack.imgur.com/5VdxN.png
Now what can I do to search only for ( 1 2 9 ) and send only the 1 2 9 to console ?

解决方案

This reply assumes you have successfully read the data into a List<List<int>> named 'data'

private List<List<int>> data = new List<List<int>>
{
    new List<int>{ 1, 2, 3}, new List<int>{1, 2, 9}, new List<int>{4, 3, 2}
};

// note return value is a nullable int
private int? findTuplet(params int[] ints)
{

// begin edit 1

    // since the frequency of change in the values of each column
    // is: column2 => column1 => column0
    // search may be speeded up by the change in comparison order
    // shown in bold here

    // this will stop when first match is found
    //var match = data.FirstOrDefault(lst => 
    //    lst[2] == ints[2] && lst[1] == ints[1] && lst[0] == ints[0]
    //);

    // or ... use compound Where statements
    // but, potentially more evaluations here
    var match = data
        .Where(dat => dat[2] == ints[2])
        .Where(dat => dat[1] == ints[1])
        .Where(dat => dat[0] == ints[0])
        .FirstOrDefault();

// end edit 1

    if (match == null) return null;

    return data.IndexOf(match);
}

// sample use:
/*
int? isMatch = findTuplet(4, 13, 2);

if (isMatch != null) Console.WriteLine("Match {0} {1}", (isMatch == null ? "not found" : "found at index: "), (isMatch != null ? isMatch.ToString() : ""));


One of many possible ways is to use Linq[^].

I'd suggest to create custom class as follow:

public class MyData
{
    private int x = 0;
    private int y = 0;
    private int z = 0;

    public MyData(int _x, int _y, int _z)
    {
        x = _x;
        y = _y;
        z = _z;
    }

    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public int Z
    {
            get { return z; }
            set { z = value; }
    }
}



Usage:

//read all lines
string[] lines = File.ReadAllLines(@"D:\Example.txt");

//query data into list of MyData class
//split data 
List<MyData> md = lines
    .Select(a=> new MyData(Convert.ToInt32(a.Split(' ')[0]),
            Convert.ToInt32(a.Split(' ')[1]),
            Convert.ToInt32(a.Split(' ')[2]))).ToList();

//filter data
var result = md.Where(item=>item.X==1 && item.Y==2 && item.Z==9);

//display in Console
foreach(var data in result)
{
    Console.WriteLine("{0} {1} {2}",data.X, data.Y, data.Z);
}



[EDIT]
If you would like to compare data via using Equals method, you have to implement Equals method[^] in your class:

//add this piece of code at the end of class definition, just before last } bracket
    public override bool Equals(Object otherData)
    {
        if (otherData == null) return false;

        return this == (MyData)otherData;
    }

   public static bool operator ==(MyData md1, MyData md2)
   {
      return md1.X == md2.X && md1.Y == md2.Y && md1.Z == md2.Z;
   }

   public static bool operator !=(MyData md1, MyData md2)
   {
      return !(md1 == md2);
   }



Usage:

//create o object - type of MyData, to use it in comparison
MyData o = new MyData(1,2,9);
//later
var result = md.Where(item=>item.Equals(o));




[/EDIT]

Good luck!


Try this one....May be it will be helpful to you

static void Main(string[] args)
{

string[] lines;
lines = System.IO.File.ReadAllLines(@"D:\Example.txt");

for (int k = 0; k<lines.length;k++)>
{
if (lines[k] == "1 2 9") //Put your input here.
{
Console.WriteLine(lines[k].ToString());
Console.ReadLine();
}
}

}


这篇关于如何在txt文件C#中搜索数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆