LINQ get items in List<attributevaluepair>

时间:2015-09-14 15:47:15

标签: c# linq

I have a table on my Database where, aside from other columns (one of which is a UniqueIdentifier) I also have one column where I have a JSON array string with values like this (formatted):

[
    {
        "AttributeId": "fe153d69-8ac1-6e0c-8793-ff0000804eb3",
        "AttributeValueId": "64163d69-8ac1-6e0c-8793-ff0000804eb3"
    },
    {
        "AttributeId": "00163d69-8ac1-6e0c-8793-ff0000804eb3",
        "AttributeValueId": "67163d69-8ac1-6e0c-8793-ff0000804eb3"
    }
]

I then have this AttributeValuePair class which will allow me to read this data on code:

public class AttributeValuePair
{
    public AttributeValuePair();

    public Guid AttributeId { get; set; }
    public Guid AttributeValueId { get; set; }
}

Whenever I get a list of items from this table, I want to be able to filter the resulting array based on only one AttributeValueId and get only the items where this is a match, independently of the value of any other attributes.

Since that on code, to read these attribute collection I must have a List<AttributeValuePair>, how in LINQ can I get the items where a particular AttributeValueId is present?

List<AttributeValuePair> attributeValuePairs = serializer.Deserialize<List<AttributeValuePair>>(item.Variant);

I've been lost at it for two hours already and can't seem to find an escape from this one.

EDIT

Being more clear about the problem, what I'm trying to do is, from a List<ProductVariation>, get the possible values for the attribute "Portions", when the attribute "Days" is the specified value. I'm having a lot of trouble using the serializer to build the LINQ statement.

//This code is wrong, I know, but I'm trying to show what I want
result = model.ProductVariations.Find(x, new {serializer.Deserialize<List<AttributeValuePair>>(item.Variant).Where(valuePair => valuePair.AttributeId == attributeId)});

2 个答案:

答案 0 :(得分:1)

Can you try

attributeValuePairs.Where(valuePair => valuePair.AttributeId == new Guid("SomeValue"));

答案 1 :(得分:0)

这个问题的答案实际上比以前预期的要简单得多:

public string SelectedVariation(string mealsAttribute, string portionsAttribute, string product)
{
    Guid productId = new Guid(product);
    CatalogManager catalogManager = CatalogManager.GetManager();
    EcommerceManager ecommerceManager = EcommerceManager.GetManager();

    RegisterOrderAccountFormModel model = new RegisterOrderAccountFormModel();
    model.Product = catalogManager.GetProduct(productId);
    List<ProductVariation> productVariationsCollection = catalogManager.GetProductVariations(productId).ToList();

    //This is the really interesting part for the answer:
    return productVariationsCollection.Where(x => x.Variant.ToLower().Contains(mealsAttribute.ToLower()) && x.Variant.ToLower().Contains(portionsAttribute.ToLower())).FirstOrDefault().Id.ToString();
}