Skip to content

Commit b60801a

Browse files
committed
Ampersand as string-concatenation (#14)
1 parent 6c48c81 commit b60801a

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/System.Linq.Dynamic.Core/ExpressionParser.cs

+12-2
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,16 @@ Expression ParseLogicalAndOr()
591591
switch (op.id)
592592
{
593593
case TokenId.Amphersand:
594-
left = Expression.And(left, right);
594+
// When at least one side of the operator is a string, consider it's a VB-style concatenation operator.
595+
// Doesn't break any other function since logical AND with a string is invalid anyway.
596+
if (left.Type == typeof(string) || right.Type == typeof(string))
597+
{
598+
left = GenerateStringConcat(left, right);
599+
}
600+
else
601+
{
602+
left = Expression.And(left, right);
603+
}
595604
break;
596605
case TokenId.Bar:
597606
left = Expression.Or(left, right);
@@ -2298,9 +2307,10 @@ static Expression GenerateSubtract(Expression left, Expression right)
22982307

22992308
static Expression GenerateStringConcat(Expression left, Expression right)
23002309
{
2310+
// Allow concat String with something else
23012311
return Expression.Call(
23022312
null,
2303-
typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }),
2313+
typeof(string).GetMethod("Concat", new[] { left.Type, right.Type }),
23042314
new[] { left, right });
23052315
}
23062316

test/System.Linq.Dynamic.Core.Tests/ExpressionTests.cs

+15
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,21 @@ namespace System.Linq.Dynamic.Core.Tests
88
{
99
public class ExpressionTests
1010
{
11+
[Fact]
12+
public void ExpressionTests_StringConcatenation()
13+
{
14+
//Arrange
15+
var baseQuery = new[] { new { First = "FirstName", Last = "LastName" } }.AsQueryable();
16+
17+
//Act
18+
var result1 = baseQuery.Select<string>("it.First + \" \" + it.Last");
19+
var result2 = baseQuery.Select<string>("it.First & \" \" & it.Last");
20+
21+
//Assert
22+
Assert.Equal("FirstName LastName", result1.First());
23+
Assert.Equal("FirstName LastName", result2.First());
24+
}
25+
1126
[Fact]
1227
public void ExpressionTests_Double()
1328
{

0 commit comments

Comments
 (0)