【问题标题】:Combine duplicate selections into a single result将重复的选择组合成一个结果
【发布时间】:2014-10-27 22:17:46
【问题描述】:

除了我的previous question,我的问题仍然没有具体的解决方案。

我有 2 个这样的课程:

public class Product
{
    public Product()
    {
        Options = new List<Option>();
    }
    public string Name { get; set; }
    public int ID { get; set; }
    public List<Option> Options { get; set; }
}

public class Option
{
    public int SubID { get; set; }
    public string SubName { get; set; }
    public int ListBoxID { get; set; }
    public decimal Price { get; set; }
    public bool IsSelected { get; set; }
}

在这样的列表中使用:

List<Product> Products { get; set; }

当用户选择左侧的产品(始终具有相同的属性)时,它的内部 List&lt;Optie&gt; 将加载到 4 个不同的 ListBox's 中,由 ListBoxID 过滤。

现在,如果用户在 2 个产品中选择相同的选项,我如何使用 linq 将它们转换为一个结果?

例如加载了 4 个相同的产品,用户为 2 个产品选择相同的选项,那么我的结果是:

2x Product 2x lookbrood 2x ollema 2x fitness broodje 2x testtest

如果其他 2 种产品有不同的选择,则可能是它们的结果:

2x Product 2x ciabatta broodje 2x ollema 2x slagroom 2x smos

我总是需要将数量加载到Products: 例如:加载了 6 个产品,那么我的组合可以是:

3x Product 3x ciabatta broodje 3x ollema 3x slagroom 3x smos

3x Product 3x Some other option 1 3x Some other option 2 3x Some other option 3 3x Some other option 4

2x Product 2x Some option 1 2x Some option 2 2x Some option 3 2x Some option 4

2x Product 2x Some other option 1 2x Some other option 2 2x Some other option 3 2x Some other option 4

2x Product 2x Some other option 1 2x Some other option 2 2x Some other option 3 2x Some other option 4

这是我能给出的最好的解释,希望图片对你有帮助。

【问题讨论】:

  • 如果您可以举一个 2 Product 及其 Optie (选项?)的示例,以及如果选择了这 2 个 Product,结果应该是什么样子的,这可能会更清楚。最终结果的类型应该是什么?应该是单个Product 吗? List&lt;Product&gt;? Optie 应该如何组合?
  • 啊……你为什么要混合这样的语言?您有一个名为 IsSelected 的属性(不错的英文名称)......然后是一堆非英文属性(包括类名)。如果您曾经从另一个国家/地区获得编码器,那么您的代码对他/她来说将是地狱般的工作。除此之外,我无法完全弄清楚您要做什么。 :|
  • @MattBurland 更新了我的问题,我知道这是一件复杂的事情..
  • @Shaamaan 这就是我自己开发的原因 ;-),但我为你更新了属性名称

标签: c# wpf linq list


【解决方案1】:

您在寻找GroupBy吗?这会将具有相同 ID 的 Opties 分组,并为您提供它们的数量。

Product.Opties
    .GroupBy(x => new {
        x.ListBoxID, x.Naam
    })
    .Select(x => 
    new { 
        ListBoxID = x.Key.ListBoxID,
        Naam = x.Key.Naam,
        Count = x.Count()
    })

More info on GroupBy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多