This question already has answers here:
C# Declare variable in lambda expression
(3 answers)
Closed 7 years ago.
How can i declare variables in below method
For example:
double price = double.Parse(((TextBox)r.FindControl("txtUnitprice")).Text);
double total = GvProducts.Rows
.Cast<GridViewRow>()
.Where(r => ((CheckBox)r.FindControl("chkSel")).Checked)
.Sum(r =>
double.Parse(((TextBox)r.FindControl("txtQuantity")).Text) *
double.Parse(((TextBox)r.FindControl("txtUnitprice")).Text));
When any method expects a Func you have two possibilites (or to be exact three).
Add a single-line-expression (as already done)
Add the name of a delegate:
Sum(x => MyMethod(x))
Where MyMethod is a method within your class returning an int and expecting a T).
Add a multi-line expression embraced in curly brackets:
Sum(x => { /* any statements */ })
Related
This question already has answers here:
Pass Method as Parameter using C#
(13 answers)
Passing methods as parameter vs calling methods directly
(5 answers)
C# method as parameter
(4 answers)
Pass method as parameter [duplicate]
(4 answers)
Closed 1 year ago.
I searched all over for a way to pass ToUpper or ToLower as a parameter. I looked at actions, I looked at delegates, I looked at extension methods, and I looked at Microsoft documentation. The closest answer I got was: Passing an extension method to a method expecting a delegate. How does this work?, but that didn't really explain how to do it. I am writing this question in case someone else runs across a similar problem. For example, you can't pass string.ToLower() as a parameter.
The issue is figuring out:
How to call string.toLower() as a delegate?
Example of what I want to be able to do:
orderItems.GetContatenatedModdedNames(string.ToLower());
orderItems.GetConcatenatedModdedNames(string.ToUpper());
The example idea is to be able to pass in ToLower() or ToUpper() as a parameter.
Here is an example of how to do it... it involved passing an anonymous function.
public static string GetConcatenatedNames(this ICollection<OrderItem> orderItems, string separater = ",", Func<string, string> myFunc = null)
{
if (myFunc == null)
{
myFunc = x => x.ToLower();
}
var productNames = orderItems?.Select(x => x.Product)?.Select(x => myFunc(x.ProductName));
if (productNames == null)
{
return null;
}
return string.Join(separater, productNames);
}
To call this:
var upperCaseNames = orderItems.GetConcatenatedConcessionNames(myFunc: x => x.ToUpper());
This question already has answers here:
Converting a String to DateTime
(17 answers)
Closed 5 years ago.
So I am having a list with objects. Those objects have a property TimeStamp. The problem is, this property is a string. Now when sorting the list by TimeStamp, the sort function ignores "AM" and "PM"
var historicalAlarms = new List<IHistoricalAlarmItem>();
foreach(...)
{
...
}
historicalAlarms.Sort((x, y) => ((Belimed.Alarm.HistoricalAlarmItem)x).TimeStamp.CompareTo(((Belimed.Alarm.HistoricalAlarmItem)y).TimeStamp));
Is it possible to convert the TimeStamp to a new DateTime object to make the Sort function not ignore AM and PM? Remember that the objects in the List also need to be cast to another type (unfortunately they have the same name)
This works:
historicalAlarms.Sort((x, y) => ((Belimed.Alarm.HistoricalAlarmItem)x).ActivationTime.CompareTo(((Belimed.Alarm.HistoricalAlarmItem)y).ActivationTime));
This doesnt:
historicalAlarms.OrderBy(x => DateTime.Parse((Belimed.Alarm.HistoricalAlarmItem)x.TimeStamp))
You can use OrderBy and DateTime.Parse to achieve that.
historicalAlarms = historicalAlarms
.OrderBy(value => DateTime.Parse(value.TimeStamp))
.ToList();
This question already has answers here:
C# Conditional Operator Not a Statement?
(9 answers)
Closed 6 years ago.
Why is this code not valid? Pretty sure it's legit in C /C++
Pseudocode:
String s = Console.ReadLine();
int x = 0;
Int32.TryParse(s, out x) ? Console.WriteLine("Foo") : Console.WriteLine("bar");
The ternary operator is used to return values and those values must be assigned.
If you want to invoke void methods in a ternary operator, you can use delegates like this:
String s = Console.ReadLine();
int x = 0;
(Int32.TryParse(s, out x) ? new Action(() => Console.WriteLine("Foo")) : () => Console.WriteLine("bar"))();
console.writeline return void.. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression
MSDN
As discussed here, in C#, not every expression can be used as a statement.
This question already has answers here:
Overloading null ambiguity
(2 answers)
Closed 7 years ago.
I have two functions which differ only in their second parameter.
Example:
public IEnumerable<Thing> Get(string clause, List<Things> list)
{
}
public IEnumerable<Thing> Get(string clause, List<OtherThing> list)
{
}
I want to call the first instance of this function, but I want to pass null as the second parameter. Is there a way to specify the "type" of null?
Cast the null literal:
Get("", (List<Things>)null)
store it in a variable first:
List<Things> list = null;
Get("", list);
Use reflection. (I'm not going to show an example because it's needlessly complicated.)
This question already has answers here:
Why can't c# use inline anonymous lambdas or delegates? [duplicate]
(4 answers)
Closed 9 years ago.
I'm trying to learn C#'s restrictions on an anonymous type. Consider the following code:
var myAwesomeObject = new {
fn1 = new Func<int>(() => { return 5; }),
fn2 = () => { return 5; }
};
So we've got two properties that are actually functions:
fn1: A Func<int> that returns 5.
fn2: A lambda function that returns 5.
The C# compiler is happy to work with fn1, but complains about fn2 :
cannot assign lambda expression to anonymous type property.
Can someone explain why one is ok but the other is not?
Because there is no way for the compiler to know the type of () => { return 5; }; it could be a Func<int>, but it could also be any other delegate with the same signature (it could also be an expression tree). That's why you have to specify the type explicitly.