我的目标是将值写入存储在集合中的预先存在的.csv文件中。目前,我正在读取存储在.csv文件中的值,并使用filerhelper库将它们存储在集合中。但是,我想添加4个列字段{产品,基本价格,发货价格,总价格},然后,如果我的records
集合中的客户名称与customerandproducts
集合中的客户名称相匹配,请写入从customerandproducts
集合到我添加的4个字段的相应数据。
这是我的源代码的简化版本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FileHelpers;
namespace ReadFile
{
class Program
{
static void Main()
{
var engine = new FileHelperEngine<Orders>();
var records = engine.ReadFile("Daniel.csv");
// var customersandproducts = addresses.Select(x => new { x.Name, x.AddressLine1, x.AddressLine2, x.City, x.State, x.S_OrderId, x.PostalCode })
// .Join(products, custs => custs.S_OrderId, prod => prod.P_OrderId,(custs, prod) => new { custs.Name, custs.AddressLine1, custs.AddressLine2, custs.City, custs.State, custs.PostalCode, prod.Title, prod.Quantity, prod.ItemPrice, prod.ShippingPrice });
foreach (var record in records)
{
Console.WriteLine(record.Name);
Console.WriteLine(record.Track);
Console.WriteLine(record.Price);
}
}
}
[DelimitedRecord(",")]
public class Orders
{
public string Name;
public string Track;
public string Price;
}
}
以下是我的.csv文件中的数据:
ShipToCompanyorName,PackageTrackingNumber,ShipmentInformationTotalShipmentReferenceCharge
customer1,1Z620Y1V0347293915,12.6
customer2,1Z620Y1V0347106126,9.18
customer3,1Z620Y1V0347584931,13.63
customer4,1Z620Y1V0346366348,11.37
customer5,1Z620Y1V0348472309,31.
customer6,1Z620Y1V0348325290,31.34
我的问题:我想将{Product,Base Price,Ship Price,Total Price}添加到.csv文件的第一行,然后使用客户名称在customerandproducts
集合中填写每一列的信息作为关键。
答案 0 :(得分:1)
您可以使用两个类,然后使用AutoMapper
进行映射namespace ReadFile
{
class Program
{
static void Main(string[] args)
{
var engine = new FileHelperEngine<Orders>();
var records = engine.ReadFile("Daniel.csv");
var mapped = Mapper.Map<Orders[], MoreFields[]>(records );
// mapped is an array of the class with more fields
}
}
[DelimitedRecord(",")]
public class Orders
{
public string Name;
public string Track;
public string Price;
}
public class MoreFields: Orders
{
public string Product;
public string BasePrice;
...
}
}
答案 1 :(得分:1)
您应该使用FieldOptional
属性作为额外字段。然后它们将被忽略以进行导入,但包括用于导出。
[DelimitedRecord(",")]
public class Orders
{
public string Name;
public string Track;
public string Price;
[FieldOptional]
public string Product
[FieldOptional]
public string BasePrice
[FieldOptional]
public string ShipPrice
[FieldOptional]
public string TotalPrice
}
然后像:
var engine = new FileHelperEngine<Orders>();
var records = engine.ReadFile("Daniel.csv");
// transform the collection with a foreach loop
foreach(var record in records)
{
var customer = custs.ByName(record.Name);
record.Product = etc...
record.BasePrice = etc...
}
// write out the file including the optional fields.
engine.WriteFile("Daniel_transformed.csv", records);