Reputation: 6609
i am trying to sum collections result in linq,
Update:
Expected output in view :
Name TotalPoints
Raja 411
I have got the output, i Used Viewbag to pass the Totalpoints and Name in View. Thanks to all.
i get this error:
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
Linq Query thus far:
public ActionResult UserTotalProfile()
{
List<TotalPointsUser> onetotal = (from T1 in dbpoints.LoayaltyPointsTable
join T2 in dbpoints.LoyaltyDetailsTable on
T1.LoyaltyPointsId equals T2.LoyaltyPointsId
join T3 in dbpoints.CustomerTable on
T2.CustomerId equals T3.CustomerId
select new { T3.Name, T3.CustomerId, T1.Points,T1.LoyaltyPointsId } into x
where x.CustomerId == 1
group x by new { x.CustomerId, x.Name ,x.Points,x.LoyaltyPointsId} into g
select new TotalPointsUser
{
CustomerId = g.Key.CustomerId,
Name = g.Key.Name,
Points = g.Key.LoyaltyPointsId == 4 ?
((from RedeemPointsTable in dbpoints.RedeemPointsTable
where
RedeemPointsTable.CustomerId == 1
select new
{
RedeemPointsTable.Amount
}).Sum(p => p.Amount) * g.Key.Points) : g.Sum(p => p.Points)
}).ToList();
var list = onetotal.ToList();
var allpoint1 = list.Sum(a => a.Points);
var allpoint2 = onetotal.AsEnumerable().Sum(a => a.Points); // here is the error
return View(allpoint2);
}
my anonymous collections :
this is calculated total
this my View to show total:
@model IEnumerable<MvcPoints.Models.TotalPointsUser>
@{
ViewBag.Title = "UserTotalProfile";
}
@foreach (var item in Model)
{
<div >
@Html.DisplayFor(modelItem => item.Name)
</div>
<div >
Total Points <br /> <span >@Html.DisplayFor(modelItem => item.Points)</span>
</div>
}
Any help would be great.
Upvotes: 2
Views: 1152
Reputation: 1038720
The Sum
method returns an integer. So on this line, the allpoint2
variable is of type integer:
var allpoint2 = onetotal.AsEnumerable().Sum(a => a.Points);
which is what you are passing to the view:
return View(allpoint2);
But your view declaration is IEnumerable<TotalPointsUser>
@model IEnumerable<MvcPoints.Models.TotalPointsUser>
Thus the error you are getting.
You may consider using a complex view model which will contain the list of users and the sum:
public class MyViewModel
{
public int TotalSum {get; set; }
public IEnumerable<TotalPointsUser> Users { get; set; }
}
Now you could pass this view model to the view and update it's @model
definition.
Upvotes: 4