Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have looked around for some good explanations of these enumerable methods but cant seem to find one that explains it properly.
I have been using a few of them like select,skip,orderby and sort but I don't know how they actually work
For example
string[] RandomNames = names.OrderBy(x => rnd.Next()).ToArray();
or
string[] SelectedNames = names.Select(i => i.ToString()).ToArray()
So there are a few things that I am unclear of:
So what does the => actually do
How would a group by work and what would it be used for.
A brief explanation would be appreciated but an in depth explanation is what I am looking for.
=> is lambda expression.
What is lambda expression and why is so useful? Let's consider example:
You have list of random integers and you want to choose only divided by 2. In normal way it will look like that:
public bool IsDevidedByTwo(int number)
{
if(number % 2 == 0)
return true;
return false ;
}
List<int> DevidedByTwoList = new List<int>;
foreach(var number in RandomIntsList)
{
if(IsdevidedByTwo(number)) DevidedByTwoList.Add(number);
}
It easy an clear but takes lot of space so you can't understand it immediatly especially when function IsDevidedByTwo() will be in diffrent file.
How it will be look like when you use lamba expression and LINQ:
List<int> DevidedByTwoList = RandomIntsList.Where(number => number % 2 == 0).ToList();
One line instead of 12.
number => number % 2==0 is lambda expression. It's check if number is devided by 2. It works exacly like IsDevidedByTwo function but you don't need to name it.
.Where() is LINQ method witch can filter for example list and choose only elements fulfill condition in brackets.
If you want to learn more read something about LINQ and lambda expresions.
A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name.
It Reduces typing. No need to specify the name of the function, its return type, and its access modifier.When reading the code, you don't need to look elsewhere for the method's definition.
Here is a very good article with examples and explanations.
geekswithblogs
Related
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 1 year ago.
Improve this question
I was trying to make a save dialog from a rich text document but I keep getting an error on the text.
Error:
ArgumentNullException
Argument 2: cannot convert from 'char[]' to 'string[]'
I'm new to c# so I'm not sure how to fix this.
System.IO.File.WriteAllLines(ofd.FileName.ToString(), richTextBox1.Text.ToArray());
Use a different method:
System.IO.File.WriteAllText(ofd.FileName, richTextBox1.Text);
I'd recommend avoiding to use Lines for this; it's a waste of resources to split the text into N strings only to write them all back to a combined file
Why didn't your first attempt work? WriteAllLines requires an array of strings. If you call .ToArray() on a string you get an array of characters; strings and characters are very different things.
ToArray() is a LINQ method that works because a string can be treated as an enumerable sequence of char. Typically it's very rare that you would do so and you would probably use the dedicated string.ToCharArray() method if you did want a char array from a string. Mostly I use it when splitting strings on multiple characters: someString.Split(".,?!'-/:;()".ToCharArray()); as it's more readable than putting each char separately
You're more likely to use ToArray() later on for things like filtering one array using LINQ and turning the result into an array again:
Person[] smiths = people.Where(person => person.LastName == "Smith").ToArray();
Other points:
OpenFileDialog's FileName is already a string; you don't need to ToString() it
Please get into the habit of renaming your controls after you add them to a form (top of the properties grid, the (Name) line, takes two seconds). It's a lot easier for us on the internet (and you in 3 weeks' time) to be able to read usernameTextBox and go "oh, that's the username textbox" than it is to be wondering "is it textbox56 or textbox27 that is the username? I'll just go into the form designer and check.."
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
At “MSDN” it says “The range variable is like an iteration variable in a foreach statement except for one very important difference: a range variable never actually stores data from the source. It's just a syntactic convenience that enables the query to describe what will occur when the query is executed."
The example at Introduction to LINQ Queries (C#)” below is one of the few where the range and iteration variables have the same name (“num”)
// 2. Query creation.
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
Usually MSDN examples assign the range and iteration variables different names.
Are there any reasons not to use the same name for both the range variable and iteration variable when it seems convenient to do so?
At the step 2 you're building a query and at the 3 step you've already executed the query,
so the (1st)num var didn't exist at the same time to the (foreach)num var
technically both num var represent the same concept, so you can use as you want.
Generally devs user 'item' for range variable
if the foreach statement is long and complicated, i use your naming convention
...otherwise => 'item'
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))
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.
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.