Sriram Satti Sriram Satti - 2 months ago 12
C# Question

How to get the Distinct item using linq

I am banging my head with some linq query logic.

I have a some list of work orders and i will count the items for weekly total.

below is my code.

var workorder = (
from item in result1
where
GetShortDate(item.Date)>=iStartDay
&&
GetShortDate(item.Date) < isunday
&& item.WorkOrderId !=null
group item by new { item.WorkOrderId, item.Count,item.Date } into resGroup
select new {
OrderId = resGroup.Key.WorkOrderId,
Count = resGroup.Key.Count,
Date = resGroup.Key.Date
})
.Distinct()
.ToList();

var weeklycount = workorder.Sum(obj => obj.Count);


Hear my result1 input:

workorderId =1 , count = 8,date = 12/12/12
workorderId =1 , count = 8,date = 13/12/12
workorderId =2 , count = 1,date = 14/12/12


with the above logic i am getting weekly out put as 17, but i need to get only 9 because my workorderId is same for two days. no need to care about date.

How can i achieve this.can some one guide me.

Answer

Distinct will not work here, your objects are not distinct!

You need to group by workorderId and (presumably) only include the first item in the sum

var workordersForWeek = (from item in allresult
                                 where 
                                 GetShortDate(item.Date)>=iStartDay
                                 &&
                                 GetShortDate(item.Date) < isunday 
                                 && item.WorkOrderId !=null //to eleminate weekly total, which will not have workorderid
                                 group item by new { item.WorkOrderId, item.Count,item.Date } into resGroup
                                 select new {
        workOrderId=resGroup.Key.WorkOrderId,
        Count=resGroup.Key.Count,
        Date=resGroup.Key.Date
        }).GroupBy(x => x.WorkOrderId).Sum(obj => obj.First().Count)

But as you can see, this now group's the result twice. This answer will probably do what you want, but there is probably an easier way which includes not grouping by date if you dont care about the date.

You may want to try something along the lines of:

var workordersForWeek = allresult.Where(item => GetShortDate(item.Date) >= iStartDay 
                                              && GetShortDate(item.Date) < isunday 
                                              && item.WorkOrderId != null)
                                 .GroupBy(item => item.WorkOrderId, x => x.Count);

var weeklycount = workordersForWeek.Sum(x => x.First());

Untested, so not 100% sure on that.

Live example: http://rextester.com/NLC52773

Comments