使用Func <t,tresult =“”>委托</t,>

时间:2010-11-17 12:23:35

标签: c# linq

我有以下创建csv的方法。

var csv =  new CsvResult<MatrixCampaignLine>(matrixCampaignLines, fileName, CsvHelper.GetMatrixHeader(), x => x.RegionName,
                             x => x.CustomerSku.ToString(),
                             x => x.ProductName.ToString(),
                             x => x.Quantity.ToString()
 );

快乐的日子,直到我需要在最后一次属性调用中嵌入foreach。即我需要通过matrixCampaignLines.Products进行迭代。所以在x.Quantity之后想象我添加了这样的东西

x => x.Quantity.ToString(),
 foreach(var products in x => x.ProductQuantites)
        {
           x.Quantity,
         }

这是调用方法。

public CsvResult(IEnumerable<T> data, string fileName, List<string> headers, params Func<T, string>[] columns)
{
    Data = data;
    Columns = columns;
    FileName = fileName;
    Headers = headers;
}   

修改

  public IEnumerable<T> Data { get; private set; }
    public Func<T, string>[] Columns { get; private set; }
    public Func<T, string[]>[] Cols { get; private set; }
    public string FileName { get; private set; }
    public List<string> Headers { get; private set; }



    public CsvResult(IEnumerable<T> data, string fileName, List<string> headers, string userName, params Func<T, string[]>[] columns)
    {
        Data = data;
        Cols = columns;
        FileName = fileName;
        Headers = headers;
    }

1 个答案:

答案 0 :(得分:2)

一种方法是将params Func<T, string>[] columns更改为params Func<T, string[]>[] columns,将ProductQuantites作为数组返回,然后在CsvResult中展平嵌套列数组。

编辑2010-10-18

不漂亮,我希望我能提出更好的东西,但这似乎有用

var products = new List<Product> { new Product {Name="Heliamphora chimantensis", Quantity=7}, new Product {Name="Dionaea muscipula", Quantity=2}};
var mcl = new MatrixCampaignLine { RegionName = "Catalonia", CustomerSku = "4711", ProductName = "Nepenthes rajah", Quantity = 1, ProductQuantites=products };
var data = new List<MatrixCampaignLine> { mcl };
var list = new List<string> { "huvud", "axlar", "knä", "och", "tå" };
var csv = new CsvResult<MatrixCampaignLine>(data, "Jamaica Jan Sun Princess", list, "joshua", 
                x => new string[] {x.RegionName},
                x => new string[] {x.CustomerSku},
                x => new string[] {x.ProductName},
                x => new string[] {x.Quantity.ToString()},
                x => x.ProductQuantites.Select(p => p.Quantity.ToString()).ToArray()
                );