如何使我的方法通用,我可以传入属性?

时间:2017-07-27 01:41:42

标签: c# linq generics

我有以下代码,我想转变为通用方法。

    List<VariationAttribute> variationAttributeList = new List<VariationAttribute>();

    //get a distinct list of colours
    var colours = ap21Products.GroupBy(p => p.ColourCode).Select(g => g.First()); --this is different

    var colourVariationAttribute = new VariationAttribute();
    colourVariationAttribute.AttributeId = "color"; --this is different
    colourVariationAttribute.VariationAttributeId = "color"; --this is different
    colourVariationAttribute.DisplayName = new DisplayName() { Text = "Colour" }; --this is different
    colourVariationAttribute.VariationAttributeValues = new VariationAttributeValues();

    foreach (var c in colours)
    {
        var attributeValue = new VariationAttributeValue();
        attributeValue.Value = c.ColourCode; --this is different
        attributeValue.DisplayValue = new DisplayValue() { Text = c.ColourName }; --this is different

        colourVariationAttribute.VariationAttributeValues.VariationAttributeValue.Add(attributeValue);
    }
    variationAttributeList.Add(colourVariationAttribute);

我已经评论了我想要传递这些值的位置 - 字符串值很好,但我不确定如何传递动态属性名称。

例如,在第4行,它按p.ColourCode进行分组,但是我希望能够将属性传递给分组。

同样,从底部开始有4行,Text属性设置为c.ColourName,但我想传递该属性以显示在那里。

我该怎么做? 我尝试使用这样的签名但是没有成功:

private VariationAttribute createVariationAttribute<TKey>(
    IList<Ap21Product> ap21Products, 
    string attributeId,
    string attributeName,
    Func<Ap21Product, TKey> groupingProperty,
    Func<Ap21Product, TKey> groupingPropertyValue,
    )

1 个答案:

答案 0 :(得分:1)

您可以这样做:

void something(IList<Ap21Product> ap21Products,
    string attributeId,
    string attributeName,
    Func<Ap21Product, object> grouper,
    Func<Ap21Product, string> colourCode,
    Func<Ap21Product, string> displayValueText 
    )
{
    List<VariationAttribute> variationAttributeList = new List<VariationAttribute>();

    //get a distinct list of colours
    var colours = ap21Products.GroupBy(grouper).Select(g => g.First()); // this is different

    var colourVariationAttribute = new VariationAttribute();
    colourVariationAttribute.AttributeId = "color"; // this is different
    colourVariationAttribute.VariationAttributeId = "color"; // this is different
    colourVariationAttribute.DisplayName = new DisplayName() { Text = "Colour" }; // this is different
    colourVariationAttribute.VariationAttributeValues = new VariationAttributeValues();

    foreach (var c in colours)
    {
        var attributeValue = new VariationAttributeValue();
        attributeValue.Value = colourCode(c);
        attributeValue.DisplayValue = new DisplayValue() { Text = displayValueText(c) };

        colourVariationAttribute.VariationAttributeValues.VariationAttributeValue.Add(attributeValue);
    }
    variationAttributeList.Add(colourVariationAttribute);
}