我有一個包含多個欄位的 CSV 檔案(檢查下面的格式)
ArticleNumber;Shop1;Shop2;Shop3;Shop4;Shop5;Shop6;Shop7
123455;50;51;52;53;54;55;56
在欄位 Shop1,Shop2....Shop7 我有產品價格。我收到這樣的檔案,所以我需要找到一種很酷的方法來解決我的問題。我想使用 CsvHelper 庫讀取這個 CSV,但我不知道如何映射欄位。因此,我想要這樣的東西:
| 文章編號 | 店鋪 | 價錢 |
|---|---|---|
| 123455 | 店鋪 1 | 50 |
| 123455 | 店鋪 2 | 51 |
| 123455 | 店鋪 3 | 52 |
| 123455 | 店鋪 4 | 53 |
| 123455 | 店鋪 5 | 54 |
| 123455 | 店鋪 6 | 55 |
uj5u.com熱心網友回復:
我認為這會讓你得到你正在尋找的格式。
void Main()
{
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = ";"
};
using (var reader = new StringReader("ArticleNumber;Shop1;Shop2;Shop3;Shop4;Shop5;Shop6;Shop7\n123455;50;51;52;53;54;55;56\n123456;60;61;62;63;64;65;66"))
using (var csv = new CsvReader(reader, config))
{
csv.Context.RegisterClassMap<ArticleMap>();
csv.Read();
csv.ReadHeader();
var shops = csv.HeaderRecord.Skip(1).ToArray();
var records = csv.GetRecords<Article>().ToList();
var results = records.SelectMany(r => r.Shop
.Select((s, i) => new ArticleShop
{
ArticleNumber = r.ArticleNumber,
Shop = shops[i],
Price = s
})
).ToList();
}
}
public class ArticleMap : ClassMap<Article>
{
public ArticleMap()
{
Map(x => x.ArticleNumber);
Map(x => x.Shop).Index(1);
}
}
public class Article
{
public int ArticleNumber { get; set; }
public List<double> Shop { get; set; }
}
public class ArticleShop
{
public int ArticleNumber { get; set; }
public string Shop { get; set; }
public double Price { get; set; }
}
uj5u.com熱心網友回復:
您的 CSV 檔案的格式是設定的還是可以更改的?如果可以更改,您可以將其更改為
ArticleNumber;Shop;Price
123455;Shop1;50
123455;Shop2;51
等等
編輯:正如我在評論中所說,你也可以這樣做(這只是偽代碼,我沒有打開 c#)
class PriceForArticle{
int articleNumber;
string shopName;
float price;
}
然后您將使用此方法將它們初始化為 PriceForArticle 串列
List<PriceForArticle> prices = new List<PriceForArticle>();
for(int j = 1; j < AllArticles.Length; j ){
for(int i = 1; i < AllArticles[j].Length; i ){
prices.Add(new PriceForArticle(AllArticles[j][0], AllArticles[0][i], AllArticles[j][i]));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365298.html
