Need a expression to pass as parameter in c# [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using a external DLL as reference.
When i try to consume a method its asking for a expression as a parameter to filter the results.
Its expecting the type as follows
Expression<Func<Template, bool>> type as a parameter.
The template type has name and group id as properties.
I am trying to create an expression that will check if the object is equal to the group id and if the name contains in a list of items as follows.
Expression<Func<Template, bool>> filterTemplatesDestination = tmplt =>
stselectedTemplates.Contains(tmplt.Name) &&
tmplt.TemplateGroupId == stDestGroupID;
But when i assign this expression to the method i am getting an exception. If i use just the group id to filter it work fine. The expression is throwing exception when i use condition to check if the name exists in my condition.

I guess you get a NullReferenceException, I don't see any other possible exception in your code. Try this:
Expression<Func<Template, bool>> filterTemplatesDestination = tmplt =>
(stselectedTemplates!= null && tmplt.Name!=null && stselectedTemplates.Contains(tmplt.Name)) &&
tmplt.TemplateGroupId == stDestGroupID;

It seems as though your stselectedTemplate OR your tmplt.Name is null, I would take the Paolo Costa's answer and instead check for both null exceptions, but it may be better to debug your code and find exactly why those variables are returning null.

Related

using a function inside a lamba expression [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
To manage rounding there are usually two methods, the first method is round values then to sum them. Or sum values then to round them. Of course to the required precision that you want.
I want to go with the first method and I need to update this line that currently do the opposite.
this.ClonedEntity.MontantHT = ArroundDecimal.CustomDecimalArround(correctedLines.Sum(l => l.MontantHT ?? 0));
When I try to call my static method in the lambda expression it doesn't work.
How would you suggest to do it while keeping use of the linq syntax ?
Thank you.
You could try something like this:
this.ClonedEntity.MontantHT = correctedLines
.Select(x=>ArroundDecimal.CustomDecimalArround(x.MontantHT ?? 0))
.Sum();
something = correctedLines.Sum(l => ArroundDecimal.CustomDecimalArround(l.MontantHT ?? 0))

Too many "&&"s in condition coding. The better codes? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
The following code works as intended but seems inelegant.
.Where(x => x.Attributes().Contains(x.Attribute("Quick"))
&& !x.Attributes().Contains(x.Attribute("Brown"))
&& !x.Attributes().Contains(x.Attribute("Fox"))
&& !x.Attributes().Contains(x.Attribute("Jumps"))
&& !x.Attributes().Contains(x.Attribute("Lazy"))
&& !x.Attributes().Contains(x.Attribute("Dogs")))
As you can see, I am checking whether
the XElement has exactly one attribute
this attribute has the specified name
[Edit] My intention is..I want to make sure that the element has only one attribute. I mean only "Quick" attribute in this case. I know the count style though, the count does not distinguish its name.[/Edit]
[Edit2]I want elements if only if it has sigle attribute, nothing else.[/Edit2]
[Edit3]"x" is an element for instance..
<mySeg Quick="1" Brown="Two" Fox="None" Jumps="2016_En" Lazy="100" Dogs="Source"> // I do not want this XElement
or
<mySeg Quick="2" Brown="Ten"> // Nah.
or
<mySeg Quick="3"> // yes, this is one I'm looking for.
[Edit3]
[Edit4]
I guess, I have to use this one. Actually, it is the one I used before this post. I was thingking one shot.
x.Attributes().Contains(x.Attribute("Quick")) && x.Attributes().Count() == 1 //thanks Ryan
[Edit4]
If you want to ensure that it contains one and only one of a list of attributes, and you can create the list of attributes you care about, you can intersect it with the object you're examining and see if the intersection is only one item:
var attributesICareAbout = new List<Attribute>
{
AllAttributes.Attribute("Quick"),
AllAttributes.Attribute("Brown"),
AllAttributes.Attribute("Fox"),
AllAttributes.Attribute("Jumps"),
AllAttributes.Attribute("Lazy"),
AllAttributes.Attribute("Dogs")
};
// To get all items that have only a single attribute from our list and no others:
.Where(x => x.Attributes().Intersect(attributesICareAbout).Count == 1);
To get the items that have a specific attribute and no others:
// To get all the items who have only a single "Quick" attribute:
.Where(x => x.Attributes().Count(a => a == AllAttributes.Attribute("Quick")) == 1);
At first gloss, you are testing
that a specific item is present
that none of a set of other items are present
Specifically, you are looking for a succinct way to express "none of these".
Rufus almost answered this question. Set up a list using his approach.
var exclusions = new string[] { "Brown", "Fox" , "Jumps", "Lazy", "Dogs" };
Now you can test for the absence of this entire set. Remember that "none of" is the same as "not any of". We intersect the set of attribute names with the exclusion set and check whether it is empty using ! and .Any().
.Where(x => x.Attributes().Contains(x.Attribute("Quick"))
&& !a.Attributes().Select(a => a.Name).Intersect(exclusions).Any())
However
You clarified the requirements to
XElement has exactly one attribute
This attribute has a specific name
and since you already credited "Ryan" with the obvious solution to this much simpler question here I stop.
You are doing set based comparison. Here's some homework.
The join operator
Get a copy of Linqpad and use that to experiment as you learn to use Linq effectively.
Intersect
Union
Except
Join as a lambda expression is messy. I prefer the inline syntax for joins.
You may also find it useful to explore the fact that you can combine Count with Where - Count can take a lambda expression that resolves to a Boolean, just like Where, and the result is the number of items that satisfied the condition. You can use this to count along several different dimensions in a single compound condition.

ListBox get value from index [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am writing a program where you insert some numbers in a listbox and then a button click should get the values from the listbox and check whether they are positive or negative and display each other's count in a textbox.
I tried getting the value by: string x = listBox1.Items[index].Value; but it doesn't seem to work.
If you add the items to the list box as such:
listBox1.Items.Add(textBox1.Text);
Then you can retrieve the item from given index as follows:
string x = listBox1.Items[index];
The indexer is returning the value, which in that case is a string. Probably you might need to cast it to string, because the indexer actually returns object - see here: ListBox.ObjectCollection.Item Property :
string x = (string)listBox1.Items[index];
You can also try
string s = (string)listbox1.Items.GetItemAt(index);
You have to cast it to string because it's returning an object

Extract predicate from expression tree [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
HI Having that Linq query
services.Get<Container>().Where(x => x.Approval.Status == "APPROVED")
How do I get Approval.Status == "APPROVED"
This is MUCH harder to do than it seems. If the Where method is yours, and your parameter type is Expression<Func<T, bool>>, you can get the predicate as easy as myExpression.Body.
But all you'll get out of that is an Expression, which could be literally anything. You own example is a binary expression of a member expression of a member expression of a parameter expression comparing against a Constant Expression. What happens if you call a method? Like this:
services.Get<Container>().Where(x => x.IsStatus("APPROVED"))
It'll result in a completely different expression that'll require completely different handling than in your example. Even if you don't permit method calls, you still have to parse the expression to confirm it isn't one.
And because Expressions aren't language specific, ToString() can be pretty unpredictable. It's like halfway between IL and C#.
Pretty much all you can do is build an expression parser, which is quite the undertaking. If this is something you want to delve into, check out ExpressionVisitor. It provides a convenient way to iterate over and parse an Expression as you need to.

What does this C# code mean? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
FunctionThatReturnsAList(cmd)[0]
It is short-hand for:
List<Whatever> list = FunctionThatReturnsAList(cmd);
Whatever whatever = list[0];
The return type of FunctionThatReturnsAList is an object, like a List or an array that can be accessed via an indexer. The code is calling the function, which is then returning the List or array and then using the indexer to reference the first element in the collection.
An example would be:
var cmd = "123";
var returnedObj = FunctionThatReturnsAList(cmd)[0];
private List<string> FunctionThatReturnsAList(cmd)
{
return new List<string> {cmd};
}
The function returns a list, and you just access element 0 in the returned list.
Seems like cmd is an SQL command which returns may be array of some kind like DataTable[] and this function gets only first element(DataTable) from the array.
This statement can be used for all methods whose return type has a numeric indexer (e.g. lists or arrays).

Categories

Resources