c# / Linq sum where - c#

I have a table NCR containing data of the format:
ID | Date | Item | Type | Qty
1 | 01/01/13 | Apple | A | 1
2 | 01/01/13 | Apple | B | 1
3 | 01/01/13 | Orange | C | 1
4 | 01/01/13 | Orange | A | 2
6 | 01/01/13 | Orange | C | 1
I would like to produce a linq query that gives me a summary of the types and sums for a given date like so:
Item | A | B | C
Apple | 1 | 1 | 0
Orange | 2 | 0 | 2
So far I have this:
var q = data.GroupBy(l => l.Item)
.Select(g => new {
Item = g.Key,
Total = g.Sum(c => c.Qty),
A = g.Sum(c => c.Type == "A"),
B = g.Sum(c => c.Type == "B"),
C = g.Sum(c => c.Type == "C")
});
However I can't seem to give a criteria to the g.Sum lambda statement. If I use Count (which is the wrong data) I can give the critera, but why is Sum missing this? What is my alternative to creating a summary table of the data available?

The delegate provided to Sum isn't a predicate; it's a selector.
Are you trying to sum the Qty property? If so, I suspect you want:
A = g.Where(c => c.Type == "A").Sum(c => c.Qty),
B = g.Where(c => c.Type == "B").Sum(c => c.Qty),
C = g.Where(c => c.Type == "C").Sum(c => c.Qty)
(Or you could group by type as well, of course.)

Related

Converting SQL to Linq query

I'm trying to get the output of the following query into a Linq query
SELECT SearchQueries.Query,
Clicks.Name,
COUNT (SearchQueries.Query) AS Hits
FROM SearchQueries
INNER JOIN Clicks ON Clicks.SearchqueryId = SearchQueries.Id
GROUP BY SearchQueries.Query, Clicks.Name
ORDER BY Hits DESC
But I can't seem to figure out how to do this;
this is what I have so far
var result =
_db.Clicks.Select(q => q)
.GroupBy(q => q.Name, g => g.Searchquery.Query)
.ToDictionary(g=> g.Key, g => g);
but how would I continue?
the result is something like this:
+---------------+-------------------+------+
|Query | Name | Hits |
+---------------+-------------------+------+
|tag | dnfsklmfnsd | 53 |
|tag2 | dgsqfsdf | 17 |
+---------------+-------------------+------+
The original tables looks like following
SearchQueries;
+---+-------+
|Id | Query |
+---+-------+
| 1 | tag | x 53
| 2 | tag2 | x 17
+---+-------+
Clicks;
+---+-------------------+---------------+
|Id | Name | SearchqueryId |
+---+-------------------+---------------+
| 1 | dnfsklmfnsd | 1 |
| 2 | dgsqfsdf | 2 |
+---+-------------------+---------------+
Try to use GroupBy and Count: (I changed the order to using SearchQueries as "base table" in the expression, just to make it more easy to compare to the SQL-statement)
var result =
_db.SearchQueries
.GroupBy(sq => new { name = sq.Clicks.Name, query = sq.Query)
.Select(sq => new {
Query = sq.Query,
Name = sq.Clicks.Name,
Hits = sq.Count()
})
.OrderByDescending(sq => sq.Hits);
Well, if you have a navigation property Searchquery on Click, as it looks like, you can do
var result =
_db.Clicks
.GroupBy(m => new {name = m.Name, query = m.Searchquery.Query)
.Select(g => new {
Query = g.Key.query,
Name = g.Key.name,
Hits = g.Count()
});

Select all columns but group by only one in linq

I have been looking for a way to get multiple columns but group by only one in SQL and I found some info. However I can not came up with a way to do it in linq.
I have the following toy example table:
| Id | Message | GroupId | Date |
|-------------------------------|
| 1 | Hello | 1 | 1:00 |
| 2 | Hello | 1 | 1:01 |
| 3 | Hey | 2 | 2:00 |
| 4 | Dude | 3 | 3:00 |
| 5 | Dude | 3 | 3:01 |
And I would like to recover all columns for the rows that have a distinct GroupId as follows (with a 'Date' desc order):
| Id | Message | GroupId | Date |
|-------------------------------|
| 1 | Hello | 1 | 1:00 |
| 3 | Hey | 2 | 2:00 |
| 4 | Dude | 3 | 3:00 |
I do not really care about which row is picked from the grouped ones (first, second...) as long as is the only one given that group Id.
I have came out with the following code so far but it does not do what is supposed to:
List<XXX> messages = <MyRep>.Get(<MyWhere>)
.GroupBy(x => x.GroupId)
.Select(grp => grp.OrderBy(x => x.Date))
.OrderBy(y => y.First().Date)
.SelectMany(y => y).ToList();
This will give you one item per group:
List<dynamic> data = new List<dynamic>
{
new {ID = 1, Message = "Hello", GroupId = 1, Date = DateTime.Now},
new {ID = 2, Message = "Hello", GroupId = 1, Date = DateTime.Now},
new {ID = 3, Message = "Hey", GroupId = 2, Date = DateTime.Now},
new {ID = 4, Message = "Dude", GroupId = 3, Date = DateTime.Now},
new {ID = 5, Message = "Dude", GroupId = 3, Date = DateTime.Now},
};
var result = data.GroupBy(item => item.GroupId)
.Select(grouping => grouping.FirstOrDefault())
.OrderByDescending(item => item.Date)
.ToList();
//Or you can also do like this:
var result = data.GroupBy(item => item.GroupId)
.SelectMany(grouping => grouping.Take(1))
.OrderByDescending(item => item.Date)
.ToList();
If you want to control OrderBy then:
var result = data.GroupBy(item => item.GroupId)
.SelectMany(grouping => grouping.OrderBy(item => item.Date).Take(1))
.OrderByDescending(item => item.Date)
.ToList();

Combine tables using row values as column LINQ C# SQL

I have a users table:
Id | Name | Age
--------------------
1 | Steve | 21
2 | Jack | 17
3 | Alice | 25
4 | Harry | 14
I also have a table containing additional user info:
UId | Key | Value
----------------------
1 | Height | 70
2 | Height | 65
2 | Eyes | Blue
4 | Height | 51
3 | Hair | Brown
1 | Eyes | Green
The UId column links to the Id column in the users table. As you can see, not all users have the same additional info present. Alice doesn't have a height value, Jack is the only one with an eye color value etc.
Is there a way to combine this data into one table dynamically using C# and LINQ queries so that the result is something like this:
Id | Name | Age | Height | Eyes | Hair
------------------------------------------
1 | Steve | 21 | 70 | Green |
2 | Jack | 17 | 65 | Blue |
3 | Alice | 25 | | | Brown
4 | Harry | 14 | 51 |
If a user does not have a value for the column, it can remain empty/null. Does this require some sort of data pivoting?
For the case, your user info fields are constant:
var result = users.GroupJoin(details,
user => user.Id,
detail => detail.Id,
(user, detail) => new
{
user.Id,
user.Name,
user.Age,
Height = detail.SingleOrDefault(x => x.Key == "Height").Value,
Eyes = detail.SingleOrDefault(x => x.Key == "Eyes").Value,
Hair = detail.SingleOrDefault(x => x.Key == "Hair").Value,
});
You can do it by utilising GroupJoin, example:
var users = new List<Tuple<int, string, int>> {
Tuple.Create(1, "Steve", 21),
Tuple.Create(2, "Jack", 17),
Tuple.Create(3, "Alice", 25),
Tuple.Create(4, "Harry", 14)
};
var userInfos = new List<Tuple<int, string, string>> {
Tuple.Create(1, "Height", "70"),
Tuple.Create(2, "Height", "65"),
Tuple.Create(2, "Eyes", "Blue"),
Tuple.Create(4, "Height", "51"),
Tuple.Create(3, "Hair", "Brown"),
Tuple.Create(1, "Eyes", "Green"),
};
var query = users.GroupJoin(userInfos,
u => u.Item1,
ui => ui.Item1,
(u, infos) => new { User = u, Infos = infos });
var result = query.Select(qi => new
{
Id = qi.User.Item1,
Name = qi.User.Item2,
Age = qi.User.Item3,
Height = qi.Infos.Where(i => i.Item2 == "Height").Select(i => i.Item3).SingleOrDefault(),
Eyes = qi.Infos.Where(i => i.Item2 == "Eyes").Select(i => i.Item3).SingleOrDefault(),
Hair = qi.Infos.Where(i => i.Item2 == "Hair").Select(i => i.Item3).SingleOrDefault()
});
First of all I have grouped the user details data using Feature (I have renamed the Key property with Feature to avoid confusion) & UId then I have used group join to combine both results using into g. Finally retrieved the result using specified feature.
var result = from user in users
join detail in details.GroupBy(x => new { x.UId, x.Feature })
on user.Id equals detail.Key.UId into g
select new
{
Id = user.Id,
Name = user.Name,
Age = user.Age,
Height = g.FirstOrDefault(z => z.Key.Feature == "Height") != null ?
g.First(z => z.Key.Feature == "Height").First().Value : String.Empty,
Eyes = g.FirstOrDefault(z => z.Key.Feature == "Eyes") != null ?
g.First(z => z.Key.Feature == "Eyes").First().Value : String.Empty,
Hair = g.FirstOrDefault(z => z.Key.Feature == "Hair") != null ?
g.First(z => z.Key.Feature == "Hair").First().Value : String.Empty,
};
I am getting following output:-
Here is the complete Working Fiddle.
Try this
var list = (from u in context.users
join ud in context.UserDetails on u.Id equals ud.UId
select new
{
u.Id,
u.Name,
u.Age,
ud.Key,
ud.Value
});
var finallist = list.GroupBy(x => new { x.Id, x.Name,x.Age}).Select(x => new
{
x.Key.Id,
x.Key.Name,
x.Key.Age,
Height = x.Where(y => y.Key == "Height").Select(y => y.Value).FirstOrDefault(),
Eyes = x.Where(y => y.Key == "Eyes").Select(y => y.Value).FirstOrDefault(),
Hair = x.Where(y => y.Key == "Hair").Select(y => y.Value).FirstOrDefault()
}).ToList();
try this query
var objlist=( form a in contex.user
join b in contex.UserDetails on a.id equals a.Uid into gj
from subpet in gj.DefaultIfEmpty()
select new { Id=a.id, Name=a.name, Age=a.age, Height =subpet.Height,Eyes=subpet.Eyes, Hair=subpet.Hair}).ToList();

linq Group By from DataTable

I have DataTable Like this
Thank you Bob Vale for your help
what is (Select(X,i) mean in your linq,
but as i made a mistake in my table
I have this
No | Size | Type | FB | FP
----------------------------------------
100 | 2 | typeA | FB1 | A1
101 | 3 | typeB | FB1 | A1
101 | 4 | typec | FB1 | A1
103 | 4 | typeC | FB2 | A2
103 | 5 | typeD | FB2 | A2
103 | 6 | typeE | FB2 | A2
I want to have some thing like that
No | Size | Type | FB | FP
---------------------------------
100 | 2 | typeA | FB1 | A1
101 | 3 | typeB | FB1 | A1
| 4 | typec | |
103 | 4 | typeC | FB2 | A2
| 5 | typeD | |
| 6 | typeE | |
How can I make it? I can make Group By
var result = from row in cableDataTable.AsEnumerable()
group row by new
{
FB = row.Field<string>("FB"),
FP = row.Field<string>("FP"),
Size = row.Field<int>("Size"),
Type = row.Field<int>("Type"),
no= row.Field<int>("no"),
} into g
select new
{
FB = g.Key.FB,
FP = g.Key.FP,
Size = g.Key.Size,
Type = g.Key.Type
no= g.Key.no
};
but it that could't give the result
thank you for your attention
How about this:
// First declare a conversion from the DataTable to an anon type
var rows = cableDataTable.AsEnumerable()
.Select(x => new {
Size = x.Field<int>("Size"),
Type= x.Field<string>("Type"),
FB = x.Field<string>("FB"),
FP = x.Field<string>("FP")
});
// Now use group by, ordering and select many to select the rows
var result = rows.GroupBy (row => new {row.FB, row.FP} )
.OrderBy (g => g.Key.FB)
.ThenBy(g => g.Key.FP)
.SelectMany(g => g.OrderBy(row => row.Size)
.Select((x,i) =>
new {
Size = x.Size,
Type = x.Type,
FB = (i==0) ? x.FB : null,
FP= (i==0) ? x.FP : null
}));
You can use linq query as
var result = cableDataTable.AsEnumerable().GroupBy(g => new { g.FB, g.FP}).Select(x => x);

linq group by and order by on some list?

I have a list(avgEnergyObj) like
Timestamp | MeterID | Energy
----------------------------
190990001 | 1 | 98090.0
190990003 | 2 | 98909.3
190990002 | 2 | 99000.3
190990004 | 1 | 99900.9
i want to sort it by time stamp and group by meterID like -
Timestamp | MeterID | Energy
----------------------------
190990001 | 1 | 98090.0
190990003 | 2 | 99000.3
190990002 | 1 | 98909.3
190990004 | 2 | 99900.9
i have written something (not working) some error -
List<FetchingEnergy> avgEnergyObj2 =
avgEnergyObj.GroupBy(p => p.MeterId)
.Select(group =>
new {
meterID = group.Key,
FetchingEnergy = group.OrderBy(x => x.TimeStamp)
})
.OrderBy(group => group.FetchingEnergy.First().TimeStamp);
var sortedList = avgEnergyObj
.OrderBy(x => x.MeterId)
.ThenBy(x => x.TimeStamp)
.ToList();

Categories

Resources