在LINQ

时间:2017-07-06 16:35:42

标签: c# asp.net asp.net-mvc linq c#-4.0

我有一个奇怪的情况,我有两个收藏。一个集合基本上包含我的项目中的所有ItemID,其中另一个集合仅包含具有销售的ItemID(包括销售数据)。

现在我已经确定Collection#2中没有的Collections#1中的ItemID有0个销售额。现在我不确定该怎么做的情况如下:

var items = new List<Collection1>(); // Contains all ItemIDs where ItemID is a plain string

var itemsTransactions = new List<Collection2>(); // contains item id's that have sales.

现在在第三步我按itemsTransationCollection按名为Username的属性进行分组,如下所示:

var groupedByUsername = itemTransactions
    .GroupBy( x => x.Username )
    .Select( item => new MyClass
    {
        TotalItems = item
            .Select( x => x.ItemID )
            .Count(), // sub query should be performed here... ?

        SuccessfulItems = item
            .Select( x => x.ItemID )
            .Count()
    } )
    .ToList();

现在的诀窍是成功项目的计算已经正确,因为itemsTransactions集合已经包含实际上有销售的ONLY项目ID ...

我不确定如何进行上面提到的比较,将缺少的项目包含在此属性TotalItems的计数中?

所以我的问题是,是否可以在LINQ中进行分组时将子项查询添加到属性TotalItems的计数中?

有人能帮助我吗?

@DavidLee所以输出应该如下所示:

Username  TotalItems(sold + unsold)  Successful items( only ones with sales)
DavidLee    5                                                   2

xyz         4                                                   1
Ronaldo     19                                                  12 

成功的项目不应大于TotalListings(在数学上不可能)

对于@Vlad示例输入和所需输出:

项目集合

ItemID用户名

1卖方1 2卖方2 3卖方3 4卖方4 5卖方5

itemsTransactions集合:

ItemID     Username     Sales

1          Seller1       2
2          Seller2       4 
3          Seller3       5 
4          Seller4       6 
5          Seller5       7 
5          Seller5       4

itemsTransactions集合包含销售的未分组数据......这就是为什么我要将它分组到第3步......

2 个答案:

答案 0 :(得分:1)

以下是解决方案的最终版本:

   var result = itemsTransactions.GroupBy(_ => _.Name).Select(_ =>
    new
    {
        SuccessfulCount = _.Select(_ => _.ItemId).Distinct().Count(),
        TotalCount = items.Where(item => item.Name == _.Key).Select(it => it.ItemId).Distinct().Count()
    });

答案 1 :(得分:1)

我会创建两个子查询然后加入它们。我认为主要问题是使用itemsTransaction集合作为起始查询,虽然可以完成,IMO更容易从items集合开始。非常冗长,可以缩短,但我发现理解发生的事情要容易得多。

var itemsByUser = items
    .GroupBy(x => x.Username)
    .Select(x => new
    {
        Username = x.Key,
        Count = x.Count()
    };

var itemsWithSalesByUser = itemTransactions
    .GroupBy(x => x.Username)
    .Select(x => new
    {
        Username = x.Key,
        Count = x.Count()
    };

var joinedDataQuery =
    from i in itemsByUser 
    join s in itemsWithSalesByUser 
        on i.Username equals s.Username into sj
    from s in sj.DefaultIfEmpty() // left join
    select new MyClass
    {
         Username = i.Username
         TotalItems = i.Count,
         SuccessfulItems = s == null ? 0 : s.Count
    };

// this when it goes to memory so building up the queries 
// in separate variables will not have any performance impacts.
var joinedData = joinedDataQuery.ToList(); 

编辑:将=更改为equals

编辑:说明可能缺少的成功项目。