Using Linq to group, order and concatenate strings - vb.net

Suppose I have the following data
Key ID Data
A 1 Hello
A 2 World
B 2 Bar
B 1 Foo
I am looking to produce the result
A HelloWorld
B FooBar
I am struggling to get the syntax quite right - I was trying to use Aggregate, but I wasn't sure if I could (or should) use SelectMany
I'd be grateful of any help.
Dim data = result.Rows.
GroupBy(Function(r) r.Key).
Select(Function(g) g.OrderBy(Function(s) s.ID)).
Aggregate(New StringBuilder, Function(cur, nxt)
cur.Append(nxt.First.Data))
Thanks
Simon

I think this (C#) should work:
var data = from r in result.Rows
group r by r.Item("Key").ToString() into g
select new {
g.Key,
Joined = string.Join("", g.OrderBy(s => s.Item("ID"))
.Select(s => s.Item("Data")))
};

Dim result = result.Rows.GroupBy(Function(r) r.Key).Select(Function(g) New With { _
g.Key, _
String.Join("", g.OrderBy(Function(r) r.ID)) _
})

Here's an alternative implementation:
var source = new Item[]
{
new Item { Key = "A", ID = 1, Data = "Hello" },
new Item { Key = "A", ID = 2, Data = "World" },
new Item { Key = "B", ID = 2, Data = "Bar" },
new Item { Key = "B", ID = 1, Data = "Foo" }
};
var results = source
.GroupBy(item => item.Key)
.Select(group => group
.OrderBy(item => item.ID)
.Aggregate(new Item(), (result, item) =>
{
result.Key = item.Key;
result.Data += item.Data;
return result;
}));

You don't want to Aggregate the groups. You want to aggregage the elements of each group unto itself.
If you want the query to do it, then
Dim data = result.Rows
.GroupBy( )
.Select(Function(g) g
.OrderBy( )
.Aggregate( )
)
If that anonymous function starts getting too hairy to write, just make a method that accepts an IGrouping<int, Row> and turns it into what you want. Then call it like:
Dim data = result.Rows
.GroupBy( )
.Select( myMethod )

Related

how to add conditional where parameters to sql query in node js

I have the below method that aims to filter records from a table. But sometimes, the user might only select one filter or two. I want to add where conditions only for parameters that the user sends. At the moment, it filters with all conditions. One possibility I know is to use some conditions to concatenate the string if true but I do not think this is the best way.
Any better way of doing this?
// Retrieve hotels by filter
app.get('/filter', (request, response) => {
var name = request.query.name;
var country = request.query.country;
var freeWifi = request.query.freeWifi;
var freeParking = request.query.freeParking;
var restaurant = request.query.restaurant;
var pool = request.query.pool;
var gym = request.query.gym;
var airconditioning = request.query.airconditioning;
let query = `select * from hotels h inner join hotelFilters hf on h.id = hf.hotelId where h.title like "%${isNullOrUndefined(name) ? '' : name}%"
and hf.freeWifi = ${freeWifi} and hf.freeParking = ${freeParking} and hf.restaurant = ${restaurant} and hf.outdoorPool = ${pool}
and hf.airConditioning = ${airconditioning}
and hf.gym = ${gym}`;
connection.query(query, (error, result) => {
if (error) {
console.log(error, 'Error occurred with hotels/filter API...');
}
if (result.length > 0) {
response.send({
result
})
}
})
});

Entity Framework Linq to SQL expression containing LEFT JOIN

I'm attempting to translate some T-SQL to an Entity Framework Core lambda expression. It involves an inner join and a left joing with a where clause.
Here is the working SQL query:
SELECT
AspNetUsers.*, Exclusions.*
FROM
AspNetUsers
JOIN Exclusions ON
AspNetUsers.FirstName = Exclusions.FirstName
AND AspNetUsers.LastName = Exclusions.LastName
LEFT JOIN ExclusionsMatches ON
ExclusionsMatches.RowHash = Exclusions.RowHash
WHERE
ExclusionsMatches.MatchIgnoredByUserId IS NULL
Which I have thus far translated into LINQ lambda as such:
var result = _db.Users
.Join(_db.Exclusions, usr => new { usr.FirstName, usr.LastName }, Exc => new { Exc.FirstName, Exc.LastName }, (usr, Exc) => new { usr, Exc })
.GroupJoin(_db.ExclusionsMatches, i => i.Exc.RowHash, x => x.RowHash, (i, ExcMatch) => new { User = i.usr, Exc = i.Exc, ExcMatch = ExcMatch })
.SelectMany(temp => temp.ExcMatch.DefaultIfEmpty(), (temp, p) => new { User = temp.User, Exc = temp.Exc, ExcMatch = temp.ExcMatch})
This seems to give me the desired query output, but I can't seem to figure out how to get the WHERE ExclusionsMatches.MatchIgnoredByUserId IS NULL clause translated.
Any thoughts on how the WHERE might be achieved? I'm also open to changing from lambda expression to linq query expression.
Thanks!
I believe using LINQ is more readable so I can provide an answer using LINQ as below.
from user in _db.Users
join excl in _db.Exclusions on new { usr.FirstName , usr.LastName} equals {excl.FirstName , excl.LastName}
join exclMtch in _db.ExclusionsMatches on excl.RowHash equals exclMtch.RowHash into grp
from itm in grp.DefaultIfEmpty()
where itm.MatchIgnoredByUserId == null
select new {
user,
excl
}
Otherwise, if you insist on using Lambda, first you have to select the field in your final selects and then add the needed where in the end of query.
var result = _db.Users
.Join(_db.Exclusions, usr => new { usr.FirstName, usr.LastName }, Exc => new { Exc.FirstName, Exc.LastName }, (usr, Exc) => new { usr, Exc })
.GroupJoin(_db.ExclusionsMatches, i => i.Exc.RowHash, x => x.RowHash, (i, ExcMatch) => new { User = i.usr, Exc = i.Exc, ExcMatch = ExcMatch MatchIgnoredByUserId = i.MatchIgnoredByUserId })
.SelectMany(temp => temp.ExcMatch.DefaultIfEmpty(), (temp, p) => new { User = temp.User, Exc = temp.Exc, ExcMatch = temp.ExcMatch, MatchIgnoredByUserId= temp.MatchIgnoredByUserId })
.Where(q => q.MatchIgnoredByUserId == null )
Do not forget to track your query in SQL Profiler :)

custom sum elements by key using lodash

I do have two objects containing keys like
var a = {bar:[1,2], foo:[7,9]}
var b = {bar:[2,2], foo:[3,1]}
I want to get the fallowing results:
var c = {bar:[3,4], foo:[10,10]}
I already have a for logic like:
for (let key in b) {
if (a[key]) {
a[key][0] += b[key][0];
a[key][1] += b[key][1];
}
else a[key] = b[key];
}
But I would like to make this logic in a lodash way. How can I Do it?
You can use create a function that takes n objects, and collects them to an array using rest parameters. Now you can spread the array into _.mergeWith() to combine the objects, and in the customizer function sum the items in the arrays using Array.map() or lodash's _.map() and _.add():
const { mergeWith, isArray, map, add } = _
const fn = (...rest) => _.mergeWith({}, ...rest, (o = [], s) =>
map(s, (n, i) => add(n, o[i]))
)
const a = {bar:[1,2], foo:[7,9]}
const b = {bar:[2,2], foo:[3,1]}
const c = {bar:[3,2], foo:[5,6]}
const d = {bar:[4,2], foo:[5,4]}
const result = fn(a, b, c, d)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
You can also use lodash/fp to create a function that merges all values to a multidimensional array with _.mergeAllWith(), then transpose the arrays using _.zipAll(), and sums each array:
const { rest, flow, mergeAllWith, isArray, head, mapValues, zipAll, map, sum } = _
const fn = rest(flow(
mergeAllWith((o, s) => [...isArray(head(o)) ? o : [o], s]), // combine to a multidimensional array
mapValues(flow(
zipAll,
map(sum)
)),
))
const a = {bar:[1,2], foo:[7,9]}
const b = {bar:[2,2], foo:[3,1]}
const c = {bar:[3,2], foo:[5,6]}
const d = {bar:[4,2], foo:[5,4]}
const result = fn(a, b, c, d)
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>
You can accomplish this using plain JavaScript with Object.entries, concat and reduce:
const a = { bar: [1,2], foo: [7,9] };
const b = { bar: [2,2], foo: [3,1] };
const entries = Object.entries(a).concat(Object.entries(b));
const result = entries.reduce((accum, [key, val]) => {
accum[key] = accum[key] ? accum[key].map((x, i) => x + val[i]) : val;
return accum;
}, { });
console.log(result);

translating sql statement to linq

I have a working sql statement and want it as linq statement or linq methode chain.
My statement is:
SELECT T1.*
FROM (SELECT Col1, MAX(InsertDate) as Data
FROM Zugbewegungsdaten
GROUP BY Loknummer) as temp JOIN T1
ON (T1.Col1= temp.Col1
AND Zugbewegungsdaten.InsertDate= temp.Date)
WHERE Col3=1
ORDER BY Loknummer
Can anybody help me to translate it?
Edit after comment:
Ok, my result for the inner select:
var maxResult = (from data in context.T1
group data by data.Col1
into groups
select new
{
Train = groups.Key,
InsertDate= groups.Max( arg => arg.InsertDate)
}) ;
I tried the join like this:
var joinedResult = from data in context.T1
join gdata in maxResult on new
{
data.Col1,
data.InsertDate
}
equals new
{
gdata.Col1,
gdata.InsertDate
}
select data;
But i get a compiler error by the join that the typeargument are invalid.
In the case that the join works i whould use a where to filter the joinedResult.
var result = from data in joinedResult
where data.Col3 == true
select data;
After much more "try and error", I got this version it looks like it works.
var joinedResult = ( ( from data in context.T1
group data by data.Col1
into g
select new
{
Key= g.Key,
Date = g.Max( p => p.InsertDate)
} ) ).Join( context.T1,
temp => new
{
Key = temp.Key,
InsertDate = temp.Date
},
data => new
{
Key = data.Col1,
InsertDate = data.InsertDate
},
( temp,
data ) => new
{
temp,
data
} )
.Where( arg => arg.data.Col3)
.OrderBy( arg => arg.data.Col1)
.Select( arg => arg.data );
Could it be that i have to set the same property names (Key, InsertDate) by joins over multi columns?

LINQ Where Exists GROUP BY

How can i convert this in LINQ?
SELECT B.SENDER, B.SENDNUMBER, B.SMSTIME, B.SMSTEXT
FROM MESSAGES B
WHERE EXISTS ( SELECT A.SENDER
FROM MESSAGES A
WHERE A.SENDER = B.SENDER
GROUP BY A.SENDER
HAVING B.SMSTIME = MAX( A.SMSTIME))
GROUP BY B.SENDER, B.SENDNUMBER, B.SMSTIME, B.SMSTEXT ;
Thanks a lot :)
EDIT!!
Resolved with:
var Condition = "order by SMSTime desc";
IEnumerable<ClassMessaggio> messaggi = Database.Select<ClassMessaggio>(Condition);; // Load all but sorted
ElencoConversazioni = messaggi.GroupBy(m => new { m.Number })
.Select(g => g.OrderByDescending(m => m.SMSTime).First()).ToObservableCollection();
Try
db.Messages.Where(b => b.SmsTime == Messages.Where(a => a.Sender == b.Sender)
.Max(a => a.SmsTime))
Or
db.Messsages.GroupBy(m => new { m.Sender, m.SendNumber })
.Select(g => g.OrderByDescending(m => m.SmsTime).First())
Where db is your DataContext.
To show the list of conversations along with "the last message of every contact", you could try something like:
// a query to find the last Sms time per sender
var lastSmsQuery = from m in db.messages
group m by m.Sender into grouping
select new
{
Sender = grouping.Key,
LastSmsTime = grouping.Max(x => x.SmsTime)
};
// a query to find the messages linked to the last Sms per sender
var lastMessageQuery = from m in db.messages
join l in lastSmsQuery on new { m.Sender, m.SmsTime } equals new { l.Sender, l.LastSmsTime }
select m;
The 2-query method used is similar to that of this question from earlier today - Convert SQL Sub Query to In to Linq Lambda