Convert Linq code from VB.Net to C# (Group Join) - c#

I have to convert the following expression from VB.NET to C#:
Dim query = (From egyosztaly As UpdateItemBase In UpdateItemCollectionRemote
Group Join egystudent As UpdateItemBase In UpdateItemCollectionLocal On egyosztaly.HashCode Equals egystudent.HashCode
Into csoport = Group
From egycsoportelem In csoport.DefaultIfEmpty
Select New ComparedUpdateItem With {.Remote = egyosztaly, .Local = egycsoportelem}).ToList()
My attempt:
var query = (from egyosztaly in UpdateItemCollectionRemote
join egystudent in UpdateItemCollectionLocal on egyosztaly.HashCode equals egystudent.HashCode into csoport
from egycsoportelem in csoport.DefaultIfEmpty
select new ComparedUpdateItem() { Remote = egyosztaly, Local = egycsoportelem }).ToList();
The second "from" part is not understandable by C#.
Thanks for help!

In C# you need to be explicit when you call a method with no arguments, to provide empty parentheses. Identifiers without parens are usually considered properties, not methods (functions in vb nomenclature)
var query = (
from egyosztaly in UpdateItemCollectionRemote
join egystudent in UpdateItemCollectionLocal on egyosztaly.HashCode equals egystudent.HashCode into csoport
from egycsoportelem in csoport.DefaultIfEmpty()
select new ComparedUpdateItem() {
Remote = egyosztaly,
Local = egycsoportelem
}
).ToList();
DefaultIfEmpty is a method and you want to call it, so you need to add ()
In VB developers often don't really care about the same set of things we care about in C#; in C# we care quite a lot about things like naming and case sens:
class SomeName{ //class names PascalCase
private int _someInt; //private vars camelCase, usually underscore led
public int SomeInt { get { return _someInt; } } //public properties PascalCase
public void SomeMethod(int someArgument){ //methods PascalCase, arguments camelCase
void localFunction() { ... }; //local function, usually camelCase
int localVariable = 0; //local vars camelCase
SomeStaticClass.SomeMethodWithNoArgs(); //Static classes PascalCase, method calls with no args must include ()
someInstance.SomeMethod(1);
var x = new Thing { X = 1 }; //new calling default constructor no longer requires () if initializing properties
Thing x = new(); //but does if new stands alone
}
}
Ultimately, it's usually possible to look at some code and know what is going on just from the casing; the only time it gets hazy is in scenarios like this:
AddAction(Foo.SomeThing) //AddAction is a method that takes.. er..
Foo.SomeThing here could be a property of an instance called Foo or it could be a method of a type called Foo - when we're calling a method that takes a method (a delegate) as a parameter we pass the method name without the () - putting () would call the method and pass the result
AddAction(Foo.SomeThing) //SomeThing could be a property or a method
AddAction(Foo.SomeThing()) //SomeThing is a method, called and its return value passed to AddAction
In latest VS properties and methods are colored differently which helps with this case. For a use case where you have "a method that takes a method", you'll come across that quite a lot in LINQ, but I'll give an example using List:
var strings = new List<string>() {"hello","world"};
strings.ForEach(Console.WriteLine);
ForEach is a method that takes a method argument. List will loop over itself calling the supplied method once for every item. The method that is passed must accept a string as an argument, like Console.WriteLine does. All the strings in the list will print to the console. It's legal to pass the method name without the () because we don't want to call the WriteLine method and pass the result to ForEach (actually WriteLine has no result); we want to pass the WriteLine method itself to ForEach
Similarly this syntax "creates a mini method":
x => something_here;
So this is legal too:
strings.ForEach(x => Console.WriteLine(x.ToUpper()));
The whole x => Console.WriteLine(x.ToUpper()) thing is "a method that takes a parameter called x, of type that will be deduced from ForEach's signature which for a list of strings is 'a method that takes a single string argument'". In VB the equivalent is:
strings.ForEach(Function(x) Console.WriteLine(x.ToUpper));
(And of course VB wouldnt care if if was ToUpper or ToUpper() but C# people care quite a bit about these detils because it's vital to help understand a program and get clues as to what is what) :)

Related

How to use inline method when assigning to object

With LINQ to objects is there a way to assign a property using an inline method without defining the method separately?
For example, I have a list I am iterating over (results) to create a new list (testObjects) with the assigned values from the LINQ statement. The TestProp property has complex logic to populate it, so I want to perform that logic within an inline method in the LINQ statement, rather than calling a separate method.
Lets say for simplicity sake when assigning TestProp below, I have a property on results called DriverID which is a string value. In this assignment I need to make sure that the DriverID is a GUID before assigning it, and if so, assign it to TestProp. If not assign new Guid();
var testObjects = results.Select(row => new
{
Name = row.Name,
Address = row.Address,
TestProp = //I don't want to call a method like ConvertToGUID() here, I would rather do the work directly in the LINQ statement with something like
{
//Do the work here instead by performing all the logic inline within this LINQ statement.
}
}
I know you can call a method here directly to assign TestProp, but is there a way to keep all the method logic right in the 1 LINQ call property assignment instead so I do not have to define a separate method for the work that needs to occur to get the TestProp value?
If you're using LINQ to Objects, your lambda expression only needs to be convertible to a delegate. So you can use something like:
var testObject = results.Select(row => {
// Several statements here, as you wish
int x = row.X;
int y = row.Y;
int z = x + y;
return new {
testProp = z,
...
}
});
This won't help with LINQ providers using Queryable though, as statement-bodied lambdas are not convertible to expression trees.

Method group behaving differently than lambda?

I am using Moq to mock some interface. Here it is:
var titleGenerator = new Mock<ITitleGenerator>();
titleGenerator.Setup(t => t.GenerateTitle()).Returns(Guid.NewGuid().ToString);
Console.WriteLine(titleGenerator.Object.GenerateTitle());
Console.WriteLine(titleGenerator.Object.GenerateTitle());
It prints the same value twice. But if I replace the second line with this:
titleGenerator.Setup(t => t.GenerateTitle()).Returns(() => Guid.NewGuid().ToString());
it returns unique values on each call.
I always thought method groups are just a shortcut to lambda expression. Is there any difference? I tried searching the documentations for any explanation. Can someone enlighten me?
It looks like the method group evaluates the expression once and somehow caches it? Or does it have something to do with Moq?
In your first example, you're passing the ToString function of a single Guid, which then gets called on every invocation. It's equivalent to this:
Guid guid = Guid.NewGuid();
titleGenerator.Setup(t => t.GenerateTitle()).Returns(guid.ToString)
In your second example, you're passing a function that first creates a new Guid and then invokes ToString() on it.
The difference is in the inputs. In the first case the "method group" is actually a delegate for Guid.ToString. But since it requires an instance as "input", the instance is part of the delegate expression, and so the same "input" is used each time.
It would be equivalent to:
var titleGenerator = new Mock<ITitleGenerator>();
Guid g = Guid.NewGuid();
titleGenerator.Setup(t => t.GenerateTitle()).Returns(g.ToString);
In the second case, the delegate has no input. The Guid instance is calculated within the delegate, so a new Guid is used each time.
For an equivalent example that might be easier to understand, the code:
var id = 1;
Func<string> f = id.ToString;
id = 2;
Console.WriteLine(f()); // 1
will write "1", whereas:
var id = 1;
Func<string> f = () => id.ToString();
id = 2;
Console.WriteLine(f()); // 2
will write "2".
In the first case, the delegate (Func<> instance) f is created with the value 1 as Target and the method info for string int.ToString() as Method. The later reassignment to id does not affect f.
In the second case, things will be more indirect. The compiler will generate a new method that corresponds to the => arrow. The local variable id is captured or closed over (is in the closure of the lambda). That means, behind the scenes, id is really promoted to a field somewhere (compiler's choice). When your method mentions id, it really accesses that field. And the compiler-generated method corresponding to the => arrow also reads that field. Now the Func<> is created with its Method property being this compiler-generated method. Because of all this, the result will be "2" here. That is the closure semantics of anonymous functions in C#.
Your original Moq example is just the same. The Returns overload in question takes an argument Func<TResult> valueFunction where TResult is string in your use. That valueFunction is what I called f in my simpler example.

C# syntax, assign delegate to a class, and call later

I have a bit of confusion with this C# syntax.
I'm trying to assign an arbitrary delegate to a class.
I have a delegates defined as
delegate string stringCB(string s);
delegate int intCB(int i);
I have a class
class run_by_name {
public string name {get;set;}
public Delegate method {get;set;}
};
And I'm trying to instantiate it
run_by_name myfuc = new run_by_name(){
name = "my name",
method = new stringCB(string s) {
return " testing " + s;
};
};
I'm really not clear how to assign to a delegate when there's a return type. Also I'm not sure how to call that method later on syntactically.
Why I'm doing this? Well I'm just writing some code that follows a pattern I use in JS a lot for event handling, I'm just making an "object" I can assign arbitrary functions to for a generic event handler that's created rather than defined. (important)
Also, alternatives to using delegates are welcome. :)
EDIT: How I might use it later
I don't have that written yet but Im pretty sure I'll be doing this.
List<run_by_name> callbacks = new List<run_by_name>();
/* lets say this is initialized and filled at this point */
public object FindAndRunCallback(string Name, object input) {
foreach(var cb in callbacks) {
if( cb.name == Name )
return cb.method(input);
}
return null;
}
Here's the syntax you need to get your current code working:
method = new stringCB((string s) => {
return " testing " + s;
})
Or, using lambda expressions:
method = new stringCB(s =>" testing " + s)
You could later invoke the method like so:
string result = (string) myfuc.method.DynamicInvoke("hello");
Without knowing more about your use case, it's hard to recommend other approaches, but I'd recommend at least looking into the following:
Events: Your description sounds very close to the common pattern for events and event handlers in C#. Your event defines the delegate type that is used to handle it, and code elsewhere can subscribe to that event with methods that match that delegate type. By convention, people usually pass a sender object as the first parameter, and some strongly-typed EventArgs so that subscribers don't have to guess at what data is going to be available when the event fires.
Func<> and Action<> variants: As C# has evolved into a more functional language, programmers have trended away from using custom delegate types, and toward using the provided variants of Func<> and Action<>. Since the arguments are strongly-typed still, you get most of the advantages of a compiled language, but use a little "duck typing" for the actual function you pass around.
For example, you could give your class a generic type based on what types you expect your delegate to deal with:
class run_by_name<T> {
public string name {get;set;}
public Func<T, T> method {get;set;}
};
Then use it:
var myfuc = new run_by_name<string>{
name = "my name",
method = s =>" testing " + s
};
string result = myfuc.method("hello");
dynamic: This keyword allows you to late-bind actions on any object. You lose the advantages of a compiled language, but it improves interoperability with more dynamic languages immensely. For example, an object can be created via JSON, and you can access the properties on it without declaring a special type for that object, just like you can in Javascript.
For example, if you changed your method declaration to this:
public dynamic method {get;set;}
Then you could simply say:
string result = myfuc.method("hello");
You have seceral choices. the strinCB constructor expects a method, that takes a string parameter and returns a string. If you have an existing method, you can pass it's name to the constructor, or you can create an anonymous method wither by delegate syntax like this:
method = new stringCB(delegate(string s)
{
return " testing " + s;
})
Or using a lambda expression:
method = new stringCB(s =>
{
return " testing " + s;
})
Then you can call it like this: myfuc.method.DynamicInvoke(YourParameter);
Normally, calling a delegate's method is pretty easy like this:
Func<int, int, int> sum = (x, y) => x + y;
Console.WriteLine(sum(2,3)); // with the name of delegate
Console.WriteLine(sum.Invoke(2,3)); // or using Invoke method
But in this case, you need to use DynamicInvoke because the type of your property is Delegate.
Apart from that .NET Framework has some useful built-in delegate types, such as Func,Action and Predicate etc. You can use them instead of creating your own delegate as long as they satisfy your needs. For example in this case you can use a Func<string,string> instead of stringCB.

What's the point of a lambda expression?

After reading this article, I can't figure out why lambda expressions are ever used. To be fair, I don't think I have a proper understanding of what delegates and expression tree types are, but I don't understand why anyone would use a lambda expression instead of a declared function. Can someone enlighten me?
First: brevity and locality:
Which would you rather write, read and maintain? This:
var addresses = customers.Select(customer=>customer.Address);
or:
static private Address GetAddress(Customer customer)
{
return customer.Address;
}
... a thousand lines later ...
var addresses = customers.Select(GetAddress);
What's the point of cluttering up your program with hundreds or thousands of four-line functions when you could just put the code you need where you need it as a short expression?
Second: lambdas close over local scopes
Which would you rather read, write and maintain, this:
var currentCity = GetCurrentCity();
var addresses = customers.Where(c=>c.City == currentCity).Select(c=>c.Address);
or:
static private Address GetAddress(Customer customer)
{
return customer.Address;
}
private class CityGetter
{
public string currentCity;
public bool DoesCityMatch(Customer customer)
{
return customer.City == this.currentCity;
}
}
....
var currentCityGetter = new CityGetter();
currentCityGetter.currentCity = GetCurrentCity();
var addresses = customers.Where(currentCityGetter.DoesCityMatch).Select(GetAddress);
All that vexing code is written for you when you use a lambda.
Third: Query comprehensions are rewritten to lambdas for you
When you write:
var addresses = from customer in customers
where customer.City == currentCity
select customer.Address;
it is transformed into the lambda syntax for you. Many people find this syntax pleasant to read, but we need the lambda syntax in order to actually make it work.
Fourth: lambdas are optionally type-inferred
Notice that we don't have to give the type of "customer" in the query comprehension above, or in the lambda versions, but we do have to give the type of the formal parameter when declaring it as a static method. The compiler is smart about inferring the type of a lambda parameter from context. This makes your code less redundant and more clear.
Fifth: Lambdas can become expression trees
Suppose you want to ask a web server "send me the addresses of the customers that live in the current city." Do you want to (1) pull down a million customers from the web site and do the filtering on your client machine, or (2) send the web site an object that tells it "the query contains a filter on the current city and then a selection of the address"? Let the server do the work and send you only the result that match.
Expression trees allow the compiler to turn the lambda into code that can be transformed into another query format at runtime and sent to a server for processing. Little helper methods that run on the client do not.
The primary reason you'd use a lambda over a declared function is when you need to use a piece of local information in the delegate expression. For example
void Method(IEnumerable<Student> students, int age) {
var filtered = students.Where(s => s.Age == age);
...
}
Lambdas allow for the easy capture of local state to be used within the delegate expression. To do this manually requires a lot of work because you need to declare both a function and a containing type to hold the state. For example here's the above without a lambda
void Method(IEnumerable<Student> students, int age) {
var c = new Closure() { Age = age };
var filtered = students.Where(c.WhereDelegate);
...
}
class Closure {
public int age;
bool WhereDelegate(Student s) {
return s.Age == age;
}
}
Typing this out is tedious and error prone. Lambda expressions automate this process.
Let's leave expression trees out of the equation for the moment and pretend that lambdas are just a shorter way to write delegates.
This is still a big win in the realm of statically typed languages like C# because such languages require lots of code to be written in order to achieve relatively simple goals. Do you need to compare sort an array of strings by string length? You need to write a method for that. And you need to write a class to put the method into. And then good practice dictates that this class should be in its own source file. In any but the smallest project, all of this adds up. When we 're talking about small stuff, most people want a less verbose path to the goal and lambdas are about as terse as it can get.
Furthermore, lambdas can easily create closures (capture variables from the current scope and extend their lifetime). This isn't magic (the compiler does it by creating a hidden class and performing some other transformations that you can do yourself), but it's so much more convenient than the manual alternative.
And then there are expression trees: a way for you to write code and have the compiler transform this code into a data structure that can be parsed, modified and even compiled at runtime. This is an extremely powerful feature that opens the door to impressive functionality (which I definitely consider LINQ to be). And you get it "for free".
http://msdn.microsoft.com/en-us/magazine/cc163362.aspx
Great article on what lambdas are, and why you can/should use them.
Essentially, the lambda expression
provides a shorthand for the compiler
to emit methods and assign them to
delegates; this is all done for you.
The benefit you get with a lambda
expression that you don't get from a
delegate/function combination is that
the compiler performs automatic type
inference on the lambda arguments
They are heavily used with LINQ, actually LINQ would be pretty bad without it. You can do stuff like:
Database.Table.Where(t => t.Field ==
"Hello");
They make it easy to pass a simple piece of functionality to another function. For example, I may want to perform an arbitrary, small function on every item in a list (perhaps I want to square it, or take the square root, or so on). Rather than writing a new loop and function for each of these situations, I can write it once, and apply my arbitrary functionality defined later to each item.
Lambda makes code short and sweet. Consider the following two examples:
public class Student
{
public string Name { get; set; }
public float grade { get; set; }
public static void failed(List<Student> studentList, isFaild fail)
{
foreach (Student student in studentList)
{
if(fail(student))
{
Console.WriteLine("Sorry" + " "+student.Name + " "+ "you faild this exam!");
}
}
}
public delegate bool isFaild(Student myStudent);
class Program
{
static void Main(string[] args)
{
List<Student> studentsList = new List<Student>();
studentsList .Add(new Student { ID = 101, Name = "Rita", grade = 99 });
studentsList .Add(new Student { ID = 102, Name = "Mark", grade = 48 });
Student.failed(studentsList, std => std.grade < 60); // with Lamda
}
}
private static bool isFaildMethod(Student myStudent) // without Lambda
{
if (myStudent.grade < 60)
{
return true;
}
else
{
return false;
}
}

Select new object as a parameter while preserving it's run-time-generated type

Consider the following:
// select a subset of the DataTable
var subset = DataTable.Where(...).Select(row => new
{
Id = Convert.ToInt32(row["Id"]),
Name = row["Name"].ToString(),
Email = row["Email"].ToString()
});
// or create a new object
var subset = new {
Id = 1,
Name = "something random",
Email = "name#domain.tld"
};
Is there any way to use the subset variable as a parameter to a method, without it being cast as a plain Object? Can you somehow carry the auto-generated type of the variable?
I am trying to avoid having to create new classes every time I want to pass LINQ subsets to methods.
Random generic approaches are welcome.
No, passing anonymous types about isn't generally a good idea because you lose the type information*. You should create a concrete type and use that instead.
var subset = DataTable.Where(...).Select(row => new SomeType
{
Id = Convert.ToInt32(row["Id"]),
Name = row["Name"].ToString(),
Email = row["Email"].ToString()
});
Alternatively you can use the Tuple type if you are using .NET 4. This is a simple way to create "disposable" types and still get some type-safety.
*Actually there is a workaround, but I regard it is an ugly hack and would advise that you don't do it.
If I need to do this, I use resharper's "Replace Anonymous Type With Named Class" refactoring option. Then you have an appropriate named type to expose over the API, and you haven't had to do any work. This also gives you options to create it immutable (like anonymous types) or mutable, nested vs top-level, etc.
BTW, I don't recommend struct here (from the question).
Another option is to pass the behaviour into the method - i.e. an Action<int,string,string> callback - then do something like:
foreach(item in query) callback(item);
However, I don't like this as it is not obvious that there is a likely error in:
DoSomething(args, (id, email, name) => Email(To: email, Subject: name));
(the error being that it should probably be (id, name, email), if you see what I mean)
You can use a generic method:
public static void Foo<T>(T item)
{
// Do whatever
}
Then if you call
Foo(subset);
the compiler will infer T for you. Whether or not that actually helps you is another matter... it depends on what the method is meant to do. Obviously Foo can't refer to Id, Name, Email etc.
In general, if multiple methods should know about the same members, then you should use a named type. The usual case for passing them to generic methods is where the method really doesn't care about what type is involved, such as in LINQ.
I've made a feature request for C# 5 that we should be able to create types which have all the same features as anonymous types (immutability, equality, hash code generation, ToString dumping) but for simple named types. We'll see if it actually happens...
Anonymous Types don't provide much help outside of the context they where created.
If you need to pass an Anonymous Type to a method, either this method is very generic like (Example)
void PrintAllObjectProperties(object obj);
witch you would use reflection to do the work, or you are doing something wrong.
Here's what I came up with...
Extension method on Object:
public static class ObjectExtensions
{
/// <summary>
/// Cast Object to anonymous type.
/// E.G.: new Object().ToAnonymousType(new { Property = new Type() });
/// </summary>
public static T ToAnonymousType<T>(this Object o, T t)
{
return (T)o;
}
}
Usage:
public void HandleAnonymousTypeAsParameter(Object o)
{
var anonymousType = o.ToAnonymousType(new
{
Id = new Int32(),
Foo = new String(),
Bar = new String()
});
// ... You can do this in even less characters:
var anonymousType = o.ToAnonymousType(new { Id = 0, Foo = "", Bar = "" });
}
HandleAnonymousTypeAsParameter(new
{
Id = 1,
Foo = "foo",
Bar = "bar"
});
Credits goes to John Skeet and Thomas P.

Categories

Resources