CsvHelper如何过滤列并仅返回不同的值

时间:2016-05-22 12:54:43

标签: c# .net linq csv

我在C#中使用CsvHelper。我想过滤我的ORIGTITLE列以获取不同的值,并将它们存储在Dictionary集合中。所以在我的Dictionary集合中我应该有以下值。我怎么能做到这一点?

  

[Abbrechen,Ab] [Abgleichen,翻译1] [Abgrenzung,Something]   [树的Baum]

我的.csv文件如下所示:

ORIGTITLE;REPLACETITLE;ORIGTOOLTIP
Abbrechen;Ab;Abbrechen
Abbrechen;Abort;abgelaufen
Abgleich;translate1;
Abgrenzung;Something;Abgrenzung zum Konto
Tree;Baum;Baum
Tree;Leaf;Baum

到目前为止,这是我的C#代码:

class DataRecord
{
    public string ORIGTITLE { get; set; }
    public string REPLACETITLE { get; set; }
    public string ORIGTOOLTIP { get; set; }
}

public void CsvReader()
    {
        using (StreamReader streamReader = new StreamReader(@"C:\Users\Devid\Desktop\Newtest.txt"))
        {
            CsvReader reader = new CsvReader(streamReader);
            reader.Configuration.Encoding = Encoding.UTF8;
            reader.Configuration.Delimiter = ";";
            List<DataRecord> records = reader.GetRecords<DataRecord>().ToList();

            //records has to be a distinct list

            Dictionary<string, string> dict = new Dictionary<string, string>();

            foreach (DataRecord record in records)
            {
                dict.Add(record.ORIGTITLE, record.REPLACETITLE);
                //i get a error because the key is not distinctq
            }
        }
    }

3 个答案:

答案 0 :(得分:1)

在添加密钥之前检查密钥是否存在:

if (!dict.ContainsKey(record.ORIGTITLE)) 
{
    dict.Add(record.ORIGTITLE, record.REPLACETITLE);
}

对于大数据集,这不会很好。考虑使用LINQ来获取不同的值。

答案 1 :(得分:1)

您可以使用LINQ按 RunOnUiThread(() => { this.GMap.MoveCamera(CameraUpdateFactory.NewLatLng(latlng)); }); 属性对记录进行分组,然后投影到字典,将ORIGTITLE作为字典键,并将每个组中的第一个ORIGTITLE作为字典值:< / p>

REPLACETITLE

答案 2 :(得分:1)

您可以使用我的CSV阅读器将结果放入数据表中。然后,您可以使用Linq获取不同的值。

你可以获得一个包含这样的代码的词典

CSVReader reader = new CSVReader();
DataTable dt =  reader.ReadCSVFile("filename", true).Tables[0];
Dictionary<int, List<DataRow>> dict = dt.AsEnumerable()
    .GroupBy(x => x.Field<int>(0), y => y)
    .ToDictionary(x => x.Key, y => y.ToList());

这是表单应用程序的类

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;
using System.Data.OleDb;
using System.Xml;
using System.Xml.Xsl;

namespace CSVImporter
{

    public partial class CSVImporter : Form
    {
        //const string xmlfilename = @"C:\Users\fenwky\XmlDoc.xml";
        const string xmlfilename = @"C:\temp\test.xml";
        DataSet ds = null;
        public CSVImporter()
        {
            InitializeComponent();
            // Create a Open File Dialog Object.
            openFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;


            //doc.InsertBefore(xDeclare, root);
            // Create a CSV Reader object.
            CSVReader reader = new CSVReader();

            ds = reader.ReadCSVFile(fileName, true);
            dataGridView1.DataSource = ds.Tables["Table1"];

        }
        private void WXML_Click(object sender, EventArgs e)
        {
            WriteXML();

        }
        public void WriteXML()
        {

            StringWriter stringWriter = new StringWriter();
            ds.WriteXml(new XmlTextWriter(stringWriter), XmlWriteMode.WriteSchema);

            string xmlStr = stringWriter.ToString();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlStr);


            XmlDeclaration xDeclare = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.InsertBefore(xDeclare, doc.FirstChild);

            // Create a procesing instruction.
            //XmlProcessingInstruction newPI;
            //String PItext = "<abc:stylesheet xmlns:abc=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">";
            //String PItext = "type='text/xsl' href='book.xsl'";
            string PItext = "html xsl:version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"";
            XmlText newPI =  doc.CreateTextNode(PItext);
            //newPI = docCreateProcessingInstruction("html", PItext);
            //newPI = doc.CreateComment(CreateDocumentType("html", PItext, "", "");
            doc.InsertAfter(newPI, doc.FirstChild);
            doc.Save(xmlfilename);

            XslCompiledTransform myXslTrans = new XslCompiledTransform();
            myXslTrans.Load(xmlfilename);
            string directoryPath = Path.GetDirectoryName(xmlfilename);
            myXslTrans.Transform(xmlfilename, directoryPath + "result.html");
            webBrowser1.Navigate(directoryPath + "result.html");

        }
    }

    public class CSVReader
    {

        public DataSet ReadCSVFile(string fullPath, bool headerRow)
        {

            string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
            string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
            DataSet ds = new DataSet();

            try
            {
                if (File.Exists(fullPath))
                {
                    string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
                    string SQL = string.Format("SELECT * FROM {0}", filename);
                    OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
                    adapter.Fill(ds, "TextFile");
                    ds.Tables[0].TableName = "Table1";
                }
                foreach (DataColumn col in ds.Tables["Table1"].Columns)
                {
                    col.ColumnName = col.ColumnName.Replace(" ", "_");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return ds;
        }
    }
}