开发者

LINQ grouping by and creating a formula based on the returned results

I need some help adding conditions to a linq query.

Take this small example

  static void Main(string[] args)
    {
        List<ItemEntry> items = new List<ItemEntry>();
        items.Add(new ItemEntry(1,1,5,1));
        items.Add(new ItemEntry(2, 1, 5, 1));
        items.Add(new ItemEntry(3, 1, 5, 1));
        items.Add(new ItemEntry(4, 1, 10, 3));
        items.Add(new ItemEntry(5, 2, 5, 1));
        items.Add(new ItemEntry(6, 2, 5, 1));
        items.Add(new ItemEntry(7, 2, 5, 1));
        items.Add(new ItemEntry(8, 2, 5, 1));
        items.Add(new ItemEn开发者_如何学Pythontry(9, 2, 5, 2));
        items.Add(new ItemEntry(10, 2, 5, 2));

        var results = from data in items
                      group data by data.ItemTypeID
                          into grouped
                          select new { ItemID = grouped.Key, ItemPrice = grouped.Sum(data => data.ItemPrice) };

        foreach (var item in results)
        {
            Console.WriteLine(item.ItemID + " " + item.ItemPrice);
        }

        Console.ReadLine();

    }
}
public class ItemEntry
{
    public int ItemID { get; set; }
    public int ItemTypeID { get; set; }
    public double ItemPrice { get; set; }
    public int ProcessedType { get; set; }

    public ItemEntry(int itemID, int itemTypeID,double itemPrice, int processedType)
    {
        ItemID = itemID;
        ItemTypeID = itemTypeID;
        ItemPrice = itemPrice;
        ProcessedType = processedType;
    }
}

I am grouping ItemTypeID then creating a sum based on the group which is fine. I now need to add an extra 2 conditions in. I want to keep the grouping the same but I want to do the same only if ProcessedType ==1 if its types 2 or 3 then I want to total them and then minus it from the grouped total.

e.g. I will use ItemTypeID 1 If I total all of ProcessedType 1 I get 15 and if I total ProcessedType3 I have 10 so I want to return 5.

I am not sure how to add the condition into my code.

Any help would be great!!!

TIA


Add a new property to your class that does the work for you.

public class ItemEntry
{
    // keep the existing properties
    ...

    public int TotalModifier
    {
        get
        {
            if (this.ProcessedType == 1)
                return this.ItemPrice;
            else
                return -(this.ItemPrice);
        }
    }

Now sum that new property

    var results = from data in items
                  group data by data.ItemTypeID
                      into grouped
                      select new { ItemID = grouped.Key, ItemPrice = grouped.Sum(data => data.TotalModifier) };

You'll want to give this property a better name than I have, but the logic is there for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜