我正在嘗試讀取此 csv 檔案,稍后我將選擇其中的不同元素并創建一個真值表,如果每個元素都存在于我放置的行中 1 如果不是 0 保持的行/行長度不是恒定的,這就是我所擁有的麻煩
chicken,other vegetables,packaged fruit/vegetables,condensed milk,frozen vegetables,fruit/vegetable juice
vinegar,oil
rolls/buns,soda,specialty bar
whole milk
pork,root vegetables,whole milk,whipped/sour cream
rolls/buns,newspapers
grapes,other vegetables,zwieback,Instant food products,dishes
frankfurter,citrus fruit,whipped/sour cream,cream cheese ,rolls/buns,baking powder,seasonal products,napkins
finished products,root vegetables,packaged fruit/vegetables,yogurt,specialty cheese,frozen vegetables,ice cream,soda,bottled beer
onions,other vegetables,flour
tropical fruit,whole milk,rolls/buns
我正在使用以下代碼
static void Main(string[] args)
{
string filepath = @"C:\Downloads\groceriess.csv";
DataTable res = ConvertCSVtoDataTable(filepath);
DataTable ConvertCSVtoDataTable(string strFilePath)
{
StreamReader sr = new StreamReader(strFilePath);
string[] headers = sr.ReadLine().Split(',');
DataTable dt = new DataTable();
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = Regex.Split(sr.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i )
{ //i did try i<rows.Length and also i < headers.Length && i <rows.Length
dr[i] = rows[i]; //this is the line that is causing the error
}
dt.Rows.Add(dr);
}
return dt;
}
}
uj5u.com熱心網友回復:
看起來問題中的代碼旨在讀取具有標題行和固定列數的 CSV 檔案。但是,這不是您的資料。
您可以做的最好的是將資料存盤在 a 中List<List<string>>,如下所示:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace Groceries
{
internal class Program
{
static List<List<string>> LoadGroceryList(string filename)
{
var groceryList = new List<List<string>>();
using (var reader = new StreamReader(filename))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var items = Regex.Split(line, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
if (items.Length > 0) { groceryList.Add(items.ToList()); }
}
}
return groceryList;
}
static void Main(string[] args)
{
string filepath = @"C:\temp\Groceries.csv";
var groceries = LoadGroceryList(filepath);
var uniqueItems = groceries.SelectMany(x => x).Distinct().OrderBy(y => y);
Console.WriteLine(string.Join("\r\n", uniqueItems));
Console.ReadLine();
}
}
}
對于問題中的資料,輸出:
baking powder
bottled beer
chicken
citrus fruit
condensed milk
cream cheese
dishes
finished products
flour
frankfurter
frozen vegetables
fruit/vegetable juice
grapes
ice cream
Instant food products
napkins
newspapers
oil
onions
other vegetables
packaged fruit/vegetables
pork
rolls/buns
root vegetables
seasonal products
soda
specialty bar
specialty cheese
tropical fruit
vinegar
whipped/sour cream
whole milk
yogurt
zwieback
uj5u.com熱心網友回復:
您的代碼意味著一行中的專案數必須完全等于header.length. 但在您的 CSV 檔案中,每一行的長度都不同。
您必須與標題長度分開檢查每行中的專案數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419184.html
標籤:
