Is it possible to filter a TextFile in listview in

2019-09-15 01:22发布

问题:

For example the value in my Textfile

1.Description=DATABASESECRIPTION1
1.name = TEST1
1.age = 18

2.Description=DATABASESECRIPTION2
2.name = TEST1
2.age = 14

3.Description=DATABASESECRIPTION3
3.name = TEST1
3.age = 18

i only wanna see

1.Description=DATABASESECRIPTION1
2.Description=DATABASESECRIPTION2
3.Description=DATABASESECRIPTION3

and i only wanna show the value of description in a textfile how can i do this ? How can i filter this.

my code

Stream mystream;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if ((mystream = openFileDialog.OpenFile()) != null)
                {
                    string strfilname= openFileDialog.FileName;
                    string filetext = File.ReadAllText(strfilname);
                    ListVIew.Text = filetext;
                }

回答1:

simply you can check if your line contains "description". if so, take rest of text from "=" char. check this:

  var list = new List<string>();
        var text = File.ReadAllLines("1.txt");
        foreach (var s in text)
        {
            if (s.Contains("Description"))
            {
                var desc = s.Substring(s.IndexOf("=") + 1);
                list.Add(desc);
            }
        }

LINQ:

list.AddRange(from s in text where s.Contains("Description") select s.Substring(s.IndexOf("=") + 1));

here is result:



回答2:

Filter for lines that contain '.Description='.

var fileLines = filetext.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ListVIew.Text = fileLines.Where(l => l.Contains(".Description="));