linq select query? - c#

ChartData
public class ChartData {
public Series[] Series { get; set; }
}
Series
public class Series{
public Strind Name { get; set; }
public Data Data { get; set; }
}
Data
public class Data {
public object[] Points { get; set; }
}
Records
Date | Name | Value
date1 | T1 | 15
date1 | T2 | 20
date2 | T1 | 25
date2 | T2 | 30
date3 | T1 | 35
date3 | T2 | 40
And linq codes
(from d in MeterReadings
group d by new { name = d.Name } into g
select new ChartData
{
Series = (from s in g
select new Series
{
Name = g.Key.name,
Data = new Data(new object[] { g.Select(x => x.Value) })
}).ToArray()
}).FirstOrDefault();
Expected:
Name = T1 , Data = 15, 25, 35
Name = T2 , Data = 20, 30, 40
But Output:
Name = T1 , Data = 15, 25, 35
Name = T1 , Data = 15, 25, 35
Name = T1 , Data = 15, 25, 35
I cant find right codes to get expected. Could you review the linq codes? Where have done wrong?
Thanks in advance.

The problem is that you select new ChartData for each grouping and then take first. Try this code:
var series = MeterReadings.GroupBy(x => x.Name)
.Select(g => new Series
{
Name = g.Key,
Data = new Data {Points = g.Select(x => x.Value).ToArray()}
})
.ToArray();
var chartData = new ChartData {Series = series};

Related

Sort List<T> on a property in a related List<T>

Say we have two List<T>. The first is a list of sales totals:
class SalesTotals
{
public Guid EmpID { get; set; }
public string EmpName { get; set; }
public decimal? TotalSales { get; set; }
}
Then we have another list of sales by year:
class YearlySales
{
public Guid EmpID { get; set; }
public short SalesYear { get; set; }
public decimal? YearlyTotals { get; set; }
}
These are used together to create a "cross tab" report which lists the total sales by each employee, followed by a column for each year with the related yearly sales. It would look something like this:
| Name | Total | 2018 | 2017 | 2016 |
+------+-------+------+------+------+
| Joe | 70 | 20 | | 50 |
| Sam | 60 | 30 | 20 | 10 |
| Fred | 50 | 30 | | 20 |
| Bob | 40 | 10 | 15 | 15 |
By default, the report is sorted by TotalSales (no problem). But if we want to sort by an individual year, things get trickier. Sorted by 2017 (then by total):
| Name | Total | 2018 | 2017 | 2016 |
+------+-------+------+------+------+
| Sam | 60 | 30 | 20 | 10 |
| Bob | 40 | 10 | 15 | 15 |
| Joe | 70 | 20 | | 50 |
| Fred | 50 | 30 | | 20 |
I assume we want to (Left) Join these two List<T>s on EmpID, where SalesYear == <year to sort by> then OrderBy YearlyTotals, TotalSales (since YearlyTotals might not exist for a given year, and we still want some type of order in that case). So we also have to consider that there might not be a record for that year to join with (so it needs to be a left join).
If I were writing SQL it would look something like this:
SELECT ST.EmpID, ST.EmpName, ST.TotalSales
FROM SalesTotals AS ST
LEFT JOIN YearlySales AS YS ON ST.EmpID=YS.EmpID
WHERE YS.SalesYear=#SortBySalesYear OR YS.SalesYear IS NULL
ORDER BY YS.YearlySales DESC, ST.TotalSales DESC
I'm not good enough with Linq (yet) to be able to figure this out. In fact, I was able to get virtually no where (maybe trying to do too much at once, perhaps I need to break it down in to individual steps, and not search for the one liner).
So, is there a way to do this with Linq? Or should I be attempting some other type of approach?
Note: All I need is an "in place" sort here. I don't need/want a different type of List<T> returned here, just a sorted List<SalesTotals>.
Edit: I prefer the Linq "Query Syntax" as it is more intuitive to me (strong SQL background). So I prefer an answer using Query Syntax as opposed to Method Syntax.
Edit: Here is a test case setup:
class SalesTotals
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal? TotalSales { get; set; }
}
class YearlySales
{
public int EmpID { get; set; }
public short SalesYear { get; set; }
public decimal? YearlyTotals { get; set; }
}
class TestSort
{
public TestSort()
{
var st = new List<SalesTotals>
{
new SalesTotals() { EmpID = 1, EmpName = "Joe", TotalSales = 70 },
new SalesTotals() { EmpID = 2, EmpName = "Sam", TotalSales = 60 },
new SalesTotals() { EmpID = 3, EmpName = "Fred", TotalSales = 50 },
new SalesTotals() { EmpID = 4, EmpName = "Bob", TotalSales = 40 }
};
var ys = new List<YearlySales>
{
new YearlySales() { EmpID = 1, SalesYear = 2018, YearlyTotals = 20 },
new YearlySales() { EmpID = 2, SalesYear = 2018, YearlyTotals = 30 },
new YearlySales() { EmpID = 3, SalesYear = 2018, YearlyTotals = 30 },
new YearlySales() { EmpID = 4, SalesYear = 2018, YearlyTotals = 10 },
new YearlySales() { EmpID = 2, SalesYear = 2017, YearlyTotals = 20 },
new YearlySales() { EmpID = 4, SalesYear = 2017, YearlyTotals = 15 },
new YearlySales() { EmpID = 1, SalesYear = 2016, YearlyTotals = 10 },
new YearlySales() { EmpID = 2, SalesYear = 2016, YearlyTotals = 15 },
new YearlySales() { EmpID = 3, SalesYear = 2016, YearlyTotals = 50 },
new YearlySales() { EmpID = 4, SalesYear = 2016, YearlyTotals = 20 }
};
st = SortByYear(st, ys, 2017);
}
private List<SalesTotals> SortByYear(List<SalesTotals> salesTotals, List<YearlySales> yearlySales, short sortYear)
{
// return sorted salesTotals by sortYear using both salesTotals and yearlySales joined on EmpID
}
}
Rather than convert the SQL directly, I think it is a little clearer to break the query into two parts.
First, find the YearlySales for the year to sort by:
var sortYearSales = from ys in yearlySales
where ys.SalesYear == SortBySalesYear
select ys;
Then you can left join on that and sort (since ys might by null, I used the null conditional member acecss operator):
var orderedSalesTotals = (from st in salesTotals
join ys in sortYearSales on st.EmpID equals ys.EmpID into ysj
from ys in ysj.DefaultIfEmpty()
orderby ys?.YearSales descending, st.TotalSales descending
select st).ToList();
Note: I changed the name of the YearlySales member to YearSales since the C# compiler complained about the member and class having the same name.
You can do it in a single query, but you must either nest the first query into the second, or use lambda syntax in the query:
var orderedSalesTotals = (from st in salesTotals
join ys in yearlySales on st.EmpID equals ys.EmpID into ysj
from ys in ysj.Where(y => y.SalesYear == SortBySalesYear).DefaultIfEmpty()
orderby ys?.YearSales descending, st.TotalSales descending
select st).ToList();
You can write it pretty much the same way you would in SQL!
var results = from t in totals
join y in years on t.EmpID equals y.EmpID into groupedTable
from p in groupedTable.DefaultIfEmpty()
where y == null || y.SalesYear == year
orderby y.SalesYear, t.TotalSales descending
select t;
Quick note: Joins in LINQ are by default inner joins. If you want an outer join, you have to use a DefaultIfEmpty() call.
Kind of works. Need to put in a null for sales
List<YearlySale> YearlySales = new List<YearlySale>() { new YearlySale() { EmpID = 1, Sales = 700, Year = 2018 },
new YearlySale() { EmpID = 1, Sales = 600, Year = 2017 },
new YearlySale() { EmpID = 1, Sales = 500, Year = 2016 },
new YearlySale() { EmpID = 2, Sales = 400, Year = 2018 },
new YearlySale() { EmpID = 2, Sales = null, Year = 2017 },
new YearlySale() { EmpID = 2, Sales = 300, Year = 2016 }
};
List<SalesTotal> SalesTotals = new List<SalesTotal>() { new SalesTotal() { EmpID = 1, EmpName = "stan", TotalSales = 1800 },
new SalesTotal() { EmpID = 2, EmpName = "sally", TotalSales = 700 }
};
var q = from s in SalesTotals
join y18 in YearlySales
on s.EmpID equals y18.EmpID
join y17 in YearlySales
on s.EmpID equals y17.EmpID
join y16 in YearlySales
on s.EmpID equals y16.EmpID
where y18.Year == 2018
where y17.Year == 2017
where y16.Year == 2016
select new { SalesTotal = s, Year18 = y18 == null ? 0 : y18.Year, YearS18 = y18 == null ? 0 : y18.Sales
, Year17 = y17 == null ? 0 : y17.Year, YearS17 = y17 == null ? 0 : y17.Sales
, Year16 = y16 == null ? 0 : y16.Year, YearS16 = y16 == null ? 0 : y16.Sales
};
foreach (var v in q.OrderBy(x => x.SalesTotal.EmpID))
{
Debug.WriteLine($"{v.SalesTotal.EmpID} {v.SalesTotal.EmpName} {v.SalesTotal.TotalSales} {v.YearS18} as y18 {v.YearS17} as y17 {v.YearS16} as y16" );
}

get List<SomeClass> after .GroupBy()

Can someone explain me how i can use GroupBy with Select to get from this:
public class BadClass{
public int id; //can be grouped by id
public string name; //identical for the same Id
public bool flag; //identical for the same Id
public int bId;
public string bName;
public int cId;
public string cName;
}
This one: List <A> where:
public class A {
public int id;
public string name;
public bool flag;
public List<B> bList;
}
public class B {
public int id;
public string name;
public C c;
}
public class C {
public int id;
public int name;
}
I make example of data in BadClass:
List<BadClass> badClass = new List<BadClass>() {
new BadClass(){ id = 1, name = "A1", flag = true, bId = 1, bName = "B1", cId = 1, cName = "C1" },
new BadClass(){ id = 1, name = "A1", flag = true, bId = 2, bName = "B2", cId = 3, cName = "C2" },
new BadClass(){ id = 1, name = "A1", flag = true, bId = 3, bName = "B3", cId = 1, cName = "C1" },
new BadClass(){ id = 2, name = "A2", flag = false, bId = 4, bName = "B4", cId = 2, cName = "C2" },
new BadClass(){ id = 2, name = "A2", flag = false, bId = 5, bName = "B5", cId = 3, cName = "C3" }
};
/*
+----+------+-------+-----+-------+-----+-------+
| id | name | flag | bId | bName | cId | cName |
+----+------+-------+-----+-------+-----+-------+
| 1 | A1 | true | 1 | B1 | 1 | C1 |
+----+------+-------+-----+-------+-----+-------+
| 1 | A1 | true | 2 | B2 | 1 | C1 |
+----+------+-------+-----+-------+-----+-------+
| 1 | A1 | true | 3 | B3 | 3 | C3 |
+----+------+-------+-----+-------+-----+-------+
| 2 | A2 | false | 4 | B4 | 2 | C2 |
+----+------+-------+-----+-------+-----+-------+
| 2 | A2 | false | 5 | B5 | 3 | C3 |
+----+------+-------+-----+-------+-----+-------+
*/
I try to make something like that:
var result = badClass.GroupBy(x => x.id).Select(x => x. ???? ) ???? =(
but don't know how to make it right.
UPDATE:
var result = badClass
.GroupBy(x => x.id)
.Select(x => new A {
id = x.Key,
name = x.First().name,
flag = x.First().flag,
bList = x.ToList()
});
here is error in bList = x.ToList(); I need to change names bId to id e.t.c.
ANSWER:
var result = badClass
.GroupBy(x => x.id)
.Select(x => new A
{
id = x.Key,
name = x.First().name,
flag = x.First().flag,
bList = badClass.Where(y => y.id == x.Key).Select(y =>
new B { id = y.bId, name = y.bName, c = new C { id = y.cId, name = y.cName } }).ToList()
});
Just add a .Select and ToList which will has all the items you need
var result = badClass.GroupBy(x => x.id).Select(x => x.ToList());
var result = badClass
.GroupBy(x => x.id)
.Select(x => new A
{
id = x.Key,
name = x.First().name,
flag = x.First().flag,
bList = badClass.Where(y => y.id == x.Key).Select(y =>
new B { id = y.bId, name = y.bName, c = new C { id = y.cId, name = y.cName } }).ToList()
});
This should get you what you want
But to be honest I would prefer a foreach loop + Dictionary for readability.

Combine duplicates in a list

In my current test project I'm looking to combine all objects in a list where one of their values is the same as in another object, I would then like to check the other values under these objects and combine them together, here's and example:
Object1
{
id = 111,
price1 = 10,
price 2 = 20
}
Object2
{
id = 222,
price1 = 10,
price 2 = 20
}
Object3
{
id = 111,
price1 = 30,
price 2 = 70
}
Object4
{
id = 444,
price1 = 15,
price 2 = 25
}
From the above Object1 and and Object3 would be combined based on their related 'id' value, their prices would then be combined and would result in the following object replacing Object1 and Object3 in a list:
NewObject
{
id = 111,
price1 = 40,
price 2 = 90
}
The end list would then look like this:
NewObject
{
id = 111,
price1 = 40,
price 2 = 90
}
Object2
{
id = 222,
price1 = 10,
price 2 = 20
}
Object4
{
id = 444,
price1 = 15,
price 2 = 25
}
So far I would go about obtaining the value using linq as follows:
Select all with the same id add thier values
Create new object with combined values for all obtained in step 1 and add to new list
Continue over list and if the 'id 'already exists in new list then ignore it as it's already been combined into the new list
Is there maybe a quicker easier way with a single LINQ statement?
var result = source
.GroupBy(x => x.id,
(key, values) => new {
id = key,
price1 = values.Sum(x => x.price1),
price2 = values.Sum(x => x.price2)
});
try group by
var combined = list.GroupBy(x => x.id, x => x).Select(x => new ListObj()
{
id = x.Key,
price1 = x.Sum(s => s.price1),
price2 = x.Sum(s => s.price2),
});
whole console app:
class Program
{
static void Main(string[] args)
{
var list = new List<ListObj>()
{
new ListObj()
{
id = 111,
price1 = 10,
price2 = 20
},
new ListObj()
{
id = 222,
price1 = 10,
price2 = 20
},
new ListObj()
{
id = 111,
price1 = 30,
price2 = 70
},
new ListObj()
{
id = 444,
price1 = 15,
price2 = 25
},
};
var combined = list
.GroupBy(x => x.id, x => x)
.Select(x => new ListObj()
{
id = x.Key,
price1 = x.Sum(s => s.price1),
price2 = x.Sum(s => s.price2),
});
Console.ReadKey();
}
}
public class ListObj
{
public int id { get; set; }
public int price1 { get; set; }
public int price2 { get; set; }
}

Complex SQL JOIN Query, min, max and date range

I have the following tables:
Readings:
+----+---------------------+-------+----------+
| Id | TimestampLocal | Value | Meter_Id |
+----+---------------------+-------+----------+
| 1 | 2014-08-22 18:05:03 | 50.5 | 1 |
| 2 | 2013-08-12 14:02:09 | 30.2 | 1 |
+----+---------------------+-------+----------+
Meters:
+----+--------+
| Id | Number |
+----+--------+
| 1 | 32223 |
+----+--------+
I need to select 2 readings for each meter, the reading with max DateTime and the reading with min DateTime, in addition to the difference between values of the two readings, something like this:
+----------+------------+----------------+------------+----------------+------------+
| Meter_Id | MaxReading | MaxReadingTime | MinReading | MinReadingTime | Difference |
+----------+------------+----------------+------------+----------------+------------+
I need a single query to achieve this for all meters within a date range in Entity Framework
i was able to get this far (get max and min readings):
SELECT
tt.*
FROM Readings tt
INNER JOIN
(
SELECT
Meter_Id,
MAX(TimeStampLocal) AS MaxDateTime,
MIN(TimeStampLocal) AS MinDateTime
FROM Readings
where TimeStampLocal > '2014-12-08'
GROUP BY Meter_Id
) AS groupedtt
ON (tt.Meter_Id = groupedtt.Meter_Id) AND
(tt.TimeStampLocal = groupedtt.MaxDateTime or tt.TimeStampLocal = groupedtt.MinDateTime)
order by Meter_Id;
Using this mockup of your actual schema and data:
class Reading
{
public int Id { get; set; }
public DateTime TimestampLocal { get; set; }
public double Value { get; set; }
public int Meter_Id { get; set; }
}
List<Reading> Readings = new List<Reading>()
{
new Reading { Id = 1, TimestampLocal = new DateTime(2014, 8, 22), Value = 50.5, Meter_Id = 1 },
new Reading { Id = 2, TimestampLocal = new DateTime(2013, 8, 12), Value = 30.2, Meter_Id = 1 },
new Reading { Id = 3, TimestampLocal = new DateTime(2013, 9, 12), Value = 35.2, Meter_Id = 1 }
};
using this linq query:
var q = from r in Readings
group r by r.Meter_Id into rGroup
select new
{
Meter_Id = rGroup.Key,
MaxReading = rGroup.OrderByDescending(x => x.TimestampLocal).First().Id,
MaxReadingTime = rGroup.OrderByDescending(x => x.TimestampLocal).First().TimestampLocal,
MinReading = rGroup.OrderBy(x => x.TimestampLocal).First().Id,
MinReadingTime = rGroup.OrderBy(x => x.TimestampLocal).First().TimestampLocal,
Difference = rGroup.OrderByDescending(x => x.TimestampLocal).First().Value -
rGroup.OrderBy(x => x.TimestampLocal).First().Value
};
produces this output:
[0] = { Meter_Id = 1, MaxReading = 1, MaxReadingTime = {22/8/2014 12:00:00 πμ},
MinReading = 2, MinReadingTime = {12/8/2013 12:00:00 πμ}, Difference = 20.3 }
which should be close to expected result.
EDIT:
You can considerably simplify the above linq query by making use of the let clause:
var q = from r in Readings
group r by r.Meter_Id into rGroup
let MaxReading = rGroup.OrderByDescending(x => x.TimestampLocal).First()
let MinReading = rGroup.OrderBy(x => x.TimestampLocal).First()
select new
{
Meter_Id = rGroup.Key,
MaxReading = MaxReading.Id,
MaxReadingTime = MaxReading.TimestampLocal,
MinReading = MinReading.Id,
MinReadingTime = MinReading.TimestampLocal,
Difference = MaxReading.Value - MinReading.Value
};
Probably not the most efficient, I admit, but that's the quickest I could come up with something without counter-verifying it myself.
SELECT m.Id AS Meter_Id, MaxReading, MaxReadingTime, MinReading, MinReadingTime, (MaxReading - MinReading) AS Difference
FROM Meters m
CROSS APPLY (SELECT MIN(Value) MinReading, TimestampLocal AS MinReadingTime FROM Readings WHERE Meter_Id = m.Id) min
CROSS APPLY (SELECT MAX(Value) MaxReading, TimestampLocal AS MaxReadingTime FROM Readings WHERE Meter_Id = m.Id) max
edit: formatting.

Selecting "custom distinct" items from a List using LINQ

I have a generic List of Policy objects.
The list contains the following data
id policyNumber policySequence otherData
1 101 1 aaaa
2 101 2 bbbb
3 101 3 cccc
4 102 1 dddd
5 103 1 eeee
6 103 2 ffff
I want to select the one row containing the highest policySequence for each policyNumber, so that I end up with the following:
id policyNumber policySequence created
3 101 3 cccc
4 102 1 dddd
6 103 2 ffff
I have a solution below using a foreach, but was wondering if there was an easier, cleaner way to do this in LINQ?
class Program
{
static void Main(string[] args)
{
List<Policy> policyList = new List<Policy>
{
new Policy {id = 1, policyNumber = 101, policySequence = 1, otherData = "aaaa"},
new Policy {id = 2, policyNumber = 101, policySequence = 2, otherData = "bbbb"},
new Policy {id = 3, policyNumber = 101, policySequence = 3, otherData = "cccc"},
new Policy {id = 4, policyNumber = 102, policySequence = 1, otherData = "dddd"},
new Policy {id = 5, policyNumber = 103, policySequence = 1, otherData = "eeee"},
new Policy {id = 6, policyNumber = 103, policySequence = 2, otherData = "ffff"}
};
List<Policy> filteredPolicyList = new List<Policy>();
foreach(var policy in policyList)
{
if(!filteredPolicyList.Exists(x => x.policyNumber == policy.policyNumber))
{
filteredPolicyList.Add(policy);
}
else
{
var currentPolicyInFilteredList = filteredPolicyList.Where(x => x.policyNumber == policy.policyNumber).First();
if (policy.policySequence > currentPolicyInFilteredList.policySequence)
{
filteredPolicyList.Remove(currentPolicyInFilteredList);
filteredPolicyList.Add(policy);
}
}
}
}
}
public class Policy
{
public int id;
public int policyNumber;
public int policySequence;
public string otherData;
}
var maxPolicies = policyList
.GroupBy(p => p.PolicyNumber)
.Select(grp => grp.OrderByDescending(p => p.PolicySequence).First());
If you're using LINQ to Objects, you could use the MoreLINQ project's DistinctBy method:
var maxPolicies = policyList.OrderByDescending(x => x.PolicySequence)
.DistinctBy(x => x.PolicyNumber);
You could group and aggregate:
var result = from p in policyList
group p by p.policyNumber into g
select new { Policy = g.Key, Max = g.Max() };

Categories

Resources