使用C#

时间:2019-04-20 05:10:31

标签: c# linq csv csvhelper

我有一个CSV文件,其中列A将根据Image 1具有重复的值。在此CSV文件中,我只希望我的datagridview显示与列A不同的值,并按照图像1跳过标题为 Name 的标题列。因此,我的datagridview应该按照Image 2显示。

但是,在下面的代码中,数据网格视图按照Image 3显示。下面是我的代码。我正在使用LinqCsvhelper。我已使用link 1link 2作为参考。希望获得帮助

第1类

    public string Name
    {
      get; set;
    }

表格3

private void Form3_Load(object sender, EventArgs e)
{ 
    //Create Datatable
    DataSet dts = new DataSet();
    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("Username", typeof(string));

    //Read the data from the CSV file
    StreamReader streamReader = new StreamReader(@"\Users\d_sim\Desktop\test.csv");
    CsvReader reader = new CsvReader(streamReader);
    reader.Configuration.Encoding = Encoding.UTF8;
    reader.Configuration.Delimiter = ",";

    //Make Class 1 into a list.
    List<Class1> records = reader.GetRecords<Class2>().ToList();

    //Only Read the applicable property and display in datagridview. IRL Class1 has many properties but I only include one in this question
    var distinctbyproperty = records.GroupBy(x => x.Name).Select(x => x.First());
    dataTable.Rows.Add(distinctbyproperty.ToString());
    dts.Tables.Add(dataTable);
    this.dataGridView1.DataSource = dataTable;
    dataGridView1.AllowUserToAddRows = false;
}

2 个答案:

答案 0 :(得分:0)

您可以通过过滤记录来实现

records.GroubBy(x => x.Name).Select(x => x.First()).Distinct();

答案 1 :(得分:0)

您进行的过滤工作正常。您只需要将每一行分别添加到dataTable中即可。

foreach (var item in distinctbyproperty)
{
    dataTable.Rows.Add(item.Name);
}