2017-07-27 36 views
0

我有下面的代碼,我想變成一個通用的方法。如何使我的方法通用,從而可以傳遞屬性?

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

你可以做這樣的事情:

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); 
} 
+0

謝謝..工作一種享受。 – Lock

相關問題