Equivalent lambda syntax for linq query - c#

I am having a mind-freeze here, but I cant seem to find the equivalent lambda syntax for -
string[] a = {"a","b","c"};
string[] b = {"1","2","3"};
var x = from a1 in a
from b1 in b
select new{a1, b1};

var x = a.SelectMany(a1=>b.Select(b1=>new {a1,b1}));

ReSharper says:
var x = a.SelectMany(a1 => b, (a1, b1) => new { a1, b1 });

Related

How to compare two string arrays and store the matching values in another string array?

string[] a = { 2; a; 3; b; 4; c}
string[] b = { 2; a; 6; c}
I want to compare this two arrays and remove the all digit(2,3,4,6)values and store match string values in another array.
I want the result like this:
string[] c = {a; c;}
I was tried this but it was adding all the values.
string[] result = a.Union(b).ToArray();
Use Intersect and Where:
string[] result = a.Intersect(b).Where(c => !char.IsDigit(c[0])).ToArray();
Based on your comment to remove or replace the colon (;):
string[] result = a.Intersect(b).Where(c => !char.IsDigit(c[0]))
.Select(c => c.Replace(';',' ')).ToArray();
you need Intersect not Union
string[] result = a.Intersect(b).ToArray();
The easiest solution would be to use Linq to do the job
int tmp;
var c = a.Where(x => b.Contains(x) && !int.TryParse(x, out tmp)).ToArray();

Multiply two lambda with Expression

Basically I am trying to multiply two lambdas with the class Expression but I don't even manage to build and can't find documentation on this. Here is my code:
var f = x=>x+2;
var g = x=>x+3;
var argX = Expression.Parameter(typeof(double), "x");
var fg = Expression.Multiply(Expression.Constant(g, typeof(Func<double, double>)), Expression.Constant(f, typeof(Func<double, double>)));
//var fg = Expression.Multiply(Expression.Constant(g),Expression.Constant(f));
var lambda = Expression.Lambda<Func<double, double>>(f3, argX);
return lambda.Compile();
Do you want something like this:
Expression<Func<double,double>> f = x => x + 2;
Expression<Func<double,double>> g = x => x + 3;
var param = Expression.Parameter(typeof(double));
var invokeF = Expression.Invoke(f, param);
var invokeG = Expression.Invoke(g, param);
var mult = Expression.Multiply(invokeF,invokeG);
var lambda = ((Expression<Func<double, double>>)Expression.Lambda(mult, param)).Compile();
If i call it this way:
lambda(3);
I get 30 as valid answer.
For this simply define f and g as Expression as well:
var argX = Expression.Parameter(typeof(double), "x");
var f = Expression.Add(argX, Expression.Constant(3.0)); // applies to x => x + 3
var g = Expression.Add(argX, Expression.Constant(2.0)); // applies to x => x + 2
var fg = Expression.Multiply(f, g); // applies to f(x) * g(x)
var lambda = Expression.Lambda<Func<double, double>>(fg, argX);
Now call it like this:
var r = lambda.Compile()(1);
Which returns 12.

Nice, clean cross join in Linq using only extension methods [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Nested “from” LINQ query expressed with extension methods
I'm sure this has been asked before, but I honestly couldn't find anything.
I'm curious what the equivalent syntax would be for the following using only built-in Linq extension methods:
var z1 =
from x in xs
from y in ys
select new { x, y };
I can get the same results with this:
var z2 = xs.SelectMany(x => ys.Select(y => new { x, y }));
But it produces different IL code, and the code is a bit convoluted and hard to understand. Is there a cleaner way to do this with extension methods?
Here's my entire test method as written:
private void Test()
{
var xs = new[] { 1D, 2D, 3D };
var ys = new[] { 4D, 5D, 6D };
var z1 =
from x in xs
from y in ys
select new { x, y };
var z2 = xs.SelectMany(x => ys.Select(y => new { x, y }));
}
Here's the [Edit: C# interp of the] IL code (using ILSpy):
private void Test()
{
double[] xs = new double[]
{
1.0,
2.0,
3.0
};
double[] ys = new double[]
{
4.0,
5.0,
6.0
};
var z =
from x in xs
from y in ys
select new
{
x = x,
y = y
};
var z2 = xs.SelectMany((double x) =>
from y in ys
select new
{
x = x,
y = y
});
}
One way would be:
var z2 = xs.SelectMany(x => ys, (x, y) => new {x, y});
If you really want to use a single LINQ extension method, then another candidate would be Join, with the outerKeySelector and innerKeySelector functions defined such that they will always produce equal values.
var z3 = xs.Join(ys, x => true, y => true, (x, y) => new { x, y });
This will, however, probably give more convoluted IL code than the nested from solution. Incidentally, MSDN uses the nested from in its example for a cross join; look at the first code snippet in How to: Perform Custom Join Operations (C# Programming Guide).

Find the intersection of two lists in linq?

I have list of int A,B. i like to do the following step in linq
list<int> c = new List<int>();
for (int i = 0; i < a.count; i++)
{
for (int j = 0; j < b.count; j++)
{
if (a[i] == b[j])
{
c.add(a[i]);
}
}
}
if its a and b is object , I need check particular properties like this manner and add list if it equals how can i do this in linq?
You could use the Intersect method:
var c = a.Intersect(b);
This return all values both in a and b. However, position of the item in the list isn't taken into account.
You can use Intersect:
var a = new List<int>();
var b = new List<int>();
var c = a.Intersect(b);
Produce a list c containing all elements that are present in both lists a and b:
List<int> c = a.Intersect(b).ToList();
The LINQ equivalent of your code is:
var c = from i in Enumerable.Range(0, a.Count)
from j in Enumerable.Range(0, b.Count)
where a[i] == b[j]
select a[i];
var cList = c.ToList();
But it's much nicer to do:
var c = from aItem in a
join bItem in b on aItem equals bItem
select aItem;
var cList = c.ToList();
But this doesn't filter duplicates. To filter duplicates completely, you can do:
var cList = a.Intersect(b).ToList();
If you want duplicates to show up as many times as they do in b, for example:
var aSet = new HashSet<int>(a);
var cList = b.Where(aSet.Contains)
.ToList();
This is my version of intersection:
var a = new List<int>();
var b = new List<int>();
// intersection
var c = a.Where(x => b.Any(y => x == y)).ToList();
As Chris mentions in his comment on the original question, the sample code provided will return duplicates in list c (see his comment for details). Intersect will only return distinct values. To duplicate the behavior of the original sample code, try this:
var c = (from value in a
where b.Contains(a)
select a);

LINQ dependent calculation assignment

I'm using the following pattern in C#:
IList<foo> x = y.Select(a => new foo
{
b = Calc1(),
c = Calc2()
}).ToList();
foreach(foo f in x)
{
f.d = b / c;
}
What I would like to do though is:
IList<foo> x = y.Select(a => new foo
{
b = Calc1(),
c = Calc2()
d = b / c;
}).ToList();
So the question is: How can you modify this pattern to allow the assignment of a value that is dependent on other values being calculated during the assignment?
(Somebody will probably point out that d should be a property that does the calculation and return a value. This is a contrived example. Assume that the value of d is calculated using other values in addition to c & b which are not available later.)
If you expand this to use the full LINQ syntax:
IList<foo> x = (from a in y
let bq = Calc1()
let cq = Calc2()
select new foo {
b = bq,
c = cq,
d = bq / cq
}).ToList();
This will get you what you want.
There was an answer recommending you repeat your method calls (ie, d = Calc1() / Calc2()) - but I would recommend against this, considering it may be possible that Calc1() and Calc2() are expensive operations, and needlessly performing them twice may have performance implications.
You can't re-use initialized properties in an initializer.
I like Erik's technique. If the query expression syntax is a bother, you can use a full-on anonymous method.
List<int> y = new List<int>() { 1, 2, 3, 4 };
var x = y.Select(a =>
{
int b = a + 1;
int c = a + 2;
int d = b / c;
return new { b = b, c = c, d = d };
});

Categories

Resources