Summing linq data by year - asp.net

I've seen dozens of posts similar to this, but I just can't get it to work.
Using asp.net MVC framework, I have a table named Contributions that contains a "ContributionDate" column and an "Amount" column. I'm loading the dates and amounts to display in a chart:
var results = db.Contributions.Where(c => c.Amount > 0);
ArrayList xValue = new ArrayList();
ArrayList yValue = new ArrayList();
results.ToList().ForEach(c => xValue.Add(c.ContributionDate));
results.ToList().ForEach(c => yValue.Add(c.Amount));
The above works. Now I'd liked to sum (i.e., total) the Amounts for each year. I've seen examples that are similar to the following, but I'm clearly clueless (in this example, the compiler doesn't like the "c.ContributionDate" in the new{} statement):
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate )
.Select(c => new {Amount = c.Sum(b => b.Amount), Date=c.ContributionDate});
Thanks for your help!

When you perform a GroupBy, the key by which you're grouping elements is represented by the Key property.
Try this:
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate )
.Select(c => new { Amount = c.Sum(b => b.Amount), Date = c.Key });
But this will group items by the entire ContributionDate value, not just by the year. To do that, you'd have to do something like this:
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate.Year)
.Select(c => new
{
Amount = c.Sum(b => b.Amount),
Date = new DateTime(c.Key, 1, 1)
});
But since this appears to be Entity Framework, you probably need to use the CreateDateTime function:
using System.Data.Entity;
...
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate.Year)
.Select(c => new
{
Amount = c.Sum(b => b.Amount),
Date = EntityFunctions.CreateDateTime(c.Key, 1, 1, 0, 0, 0)
});

Related

How to make group order

I want to make group order this table but I can not group a column.
[this is my first gridview]
This is my gridview at above. I want to transform that is like below.
[I want to transform as this]
but I can not do. I use this code:
var info = (from c in db.myTable
group c by c.name into groups
select new
{
id = groups.Key,
ogrencininAdi = groups.Select(n => n.ogrencininAdi).FirstOrDefault(),
ogrencininSoyadi = groups.Select(n => n.ogrencininSoyadi).FirstOrDefault(),
ogrenciNo = groups.Select(n => n.ogrenciNo).FirstOrDefault(),
dersinAdi = groups.Select(n => n.dersinAdi).FirstOrDefault(),
yokZamani = groups.Select(n => n.yokZamani).FirstOrDefault(),
kacinciDers = groups.Select(n => n.kacinciDers).ToList(),
}).ToList();
gridViewabsentStudent.DataSource = info;
gridViewabsentStudent.DataBind();
but I have a problem on this line:
Order = groups.Select(n => n.Order).ToList()
Order = groups.Select(n => n.Order).FirstOrDefault() is unsuccessful.
I want to a solution about this problem. I hope that I described my problem
this is my final screen.
in that column was stored:
"System.Collections.Generic.List`1[System.Nullable`1[System.Int32]]"
I want to see second photo in that column.
Looking at the last image you posted, it seems all you need is a string representation for your kacinciDers property.
changing to below in your select should work, if I understood the problem
correctly.
var g = (from c in db.myTable
group c by c.name into groups
select groups)
.AsEnumerable(); // first lets change this to Enumerable
var model = g.Select(groups => new
{
id = groups.Key,
ogrencininAdi = groups.Select(n => n.ogrencininAdi).FirstOrDefault(),
ogrencininSoyadi = groups.Select(n => n.ogrencininSoyadi).FirstOrDefault(),
ogrenciNo = groups.Select(n => n.ogrenciNo).FirstOrDefault(),
dersinAdi = groups.Select(n => n.dersinAdi).FirstOrDefault(),
yokZamani = groups.Select(n => n.yokZamani).FirstOrDefault(),
kacinciDers = string.Join(", ", groups.Select(n => n.kacinciDers.ToString()).ToList()),
}).ToList();
gridViewabsentStudent.DataSource = model;
Post a comment if that didn't work, and I will be happy to help.

In one Linq Query get back data from multiple tables

I have 3 tables:
sessions - This store information about trainings
xref_session_faculty - This cross references the trainings and the teacher
user - list of all teachers
In one(or more) LINQ query i want to get all the sessions and for each session the teachers that will be conducting the training. Each session can have zero or more teachers in the DB.
sessions = db.sessions
.Where(x => x.seminar_id == seminarId)
.ToList()
.Select((x, i) => new fees
{
id = x.id,
sessionTitle = x.title,
teacherNames = "By:" + String.Join(",",
x.xref_session_faculty.ToList()
.Select(q => db.users
.Where(m => m.id == q.user_id)
.Select(t => t.firstName).ToList()
)
)
})
.ToList();
With this the teacherNames prints out By:System.Collections.Generic.List1[System.String],System.Collections.Generic.List1[System.String].
WHat is the right query format here?
teacherNames = "By:" + String.Join(",",
x.xref_session_faculty.ToList()
.Select(q => db.users
.Where(m => m.id == q.user_id)
.Select(t => t.firstName).FirstOrDefault()
)
)
you need to change ToList to FirstOrDefault function to get correct result
private var sessions = (from session in db.sessions.Where(x => x.seminar_id == seminarId)
select new
{
id = session.id,
sessionTitle = session.title,
teacherNames = (from faculty in db.xref_session_faculty.
where (x => x.session_id == session.id)
join us in db.uses on faculty.user_id equals us.user_id
select new
{
us.firstName,
other_field_names
})
});

How to assign key and count to two different labels asp.net

I have this query:
var months = dates.GroupBy(
x => x.Value.Month).Select(g => new { Month = g.Key, Count = g.Count()});
lbl1.Text = string.Join(",", months);
How do I assign key and count to two different labels?
Try this
lblMonth.Text=months.Month;
lblCount.Text=months.Count;
Also you have to call FirstOrDefault() or ToList() in order to select data. Currently you code will not select data.
var months = dates.GroupBy(x => x.Value.Month).Select(g => new { Month = g.Key, Count = g.Count() }).FirstOrDefault();
OR
var months = dates.GroupBy(x => x.Value.Month).Select(g => new { Month = g.Key, Count = g.Count() }).ToList();
if you use ToList() than you will have to get values by index like
lblMonth.Text=months[0].Month;
lblCount.Text=months[0].Count;

using select in datatable

My Datatable is in following format.
I want to get the Netfare Where Sector is 1 and then similarly I want to get Netfare Where Sector is 2.
Thanks
You can use the DataTable.Select method to filter the result.
var sector1Results = dt.Select("Sector = 1");
var sector2Results = dt.Select("Sector = 2");
You can also use DataTable.AsEnumerable method to achieve the same
var result1 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).Select(x => x.Field<int>("Sector1"));
var result2 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 2).Select(x => x.Field<int>("Sector2"));
To select the DataRow collection, You can use this
List<DataRow> collection1 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).ToList();
List<DataRow> collection2 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).ToList();
You can also merge those condition in single statement (if you want)
List<DataRow> collection = new DataTable().AsEnumerable().Where(x => x.Field<int>("Sector") == 1 || x.Field<int>("Sector") == 2).ToList();

Find most occurrences in Linq to SQL using C#

I have the below query that gets Name and TotalPoints as follows:
var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData(Convert.ToInt32(this.ShopInstanceID), 10000, false)
.Where(row => row.RecievedPoints != "n/a")
.GroupBy(row => new { row.Name })
.Select(g => new
{
TotalPoints = g.Sum(x => Convert.ToDouble(x.RecievedPoints) * (x.Weightage.ToString() == "0.00" ? 1 : Convert.ToDouble(x.Weightage))),
Name = g.Key.Name
})
select data).ToList();
I will have data like below:
TotalPoints Name
5 A
10 B
5 C
15 D
5 E
If we observe the above list 5 is most common. I have to fetch that value from "gradeData".
How can I get that?
var mostCommon = gradeData.GroupBy(x => x.TotalPoints)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.First();
The query below gives you the most common point along with all of its associated names:
var result = gradeData.GroupBy(x => x.TotalPoints)
.OrderByDescending(x => x.Count())
.Select(g => new
{
TotalPoints = g.Key,
Names = g.Select(x => x.Name).ToList()
})
.First();

Resources