is nested Linq faster than foreach loop? [closed] - c#

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 5 years ago.
Improve this question
Is this "better", faster or easier to read:
var viewsOnSheet = templateSheet.GetAllViewports()
.Select(x => doc.GetElement(x))
.Cast<Viewport>()
.Select(x => doc.GetElement(x.ViewId))
.Cast<View>();
...than this:
foreach (ElementId id in templateSheet.GetAllViewports())
{
Viewport vp = doc.GetElement(id) as Viewport;
View v = doc.GetElement(vp.ViewId) as View;
}
They both work, I am just curious if there is some programming standard that I would be violating with so many nested Linq calls. What's easier to understand? I am personally leaning towards the foreach loop.
Thanks!

For Linq-to-objects, code with foreach is always marginally faster that equivalent LINQ call just because at the end LINQ end up with similar foreach after several method calls. For Linq-to-SQL/Linq-to-XML equivalent code with less function calls would be faster too just because you execute less code.
Note that proper matching code for more complex LINQ expressions may not be easy to write (try writing GroupBy yourself correctly) and definitely will not be shorter than LINQ.
Whether this performance different matters for your application - measure yourself against your particular performance goals.
Style of code is strictly personal preference - pick whatever works for you/your team.

Related

What is the most efficient way to split a List into two Lists based on one condition? [closed]

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 1 year ago.
Improve this question
I want to split a list into two seperate lists one with elements which fulfil the condition and another with elements that don't fulfil the condition.
A possible Solution would be this:
var listTrue = list.Where(x => x.condition());
var listFalse = list.Where(x => !x.condition());
But i am not just looking for a solution. I am looking for an efficient solution. I don't demand any performance metrics.
I would be happy to receive ideas and solutions. I would benchmark those and look if any of them make a significant performance gain.
I am also looking for a solution that is available in the .net framework 4.8.
Most efficient in terms of performance would be to do a foreach loop which will do it by O(n) complexity. Although I would recommend just using LINQ as you mentioned which will be O(2n) = O(n). If your list contains lots of rows and you really need the performance to be most efficient, go for it:
var listTrue = new List<...>();
var listFalse = new List<...>();
foreach (var item in list)
{
if (item.condition())
{
listTrue.Add(item);
}
else
{
listFalse.Add(item);
}
}
Note, you might do it in parallel also if it is logically make sense.

How to sort strings alphabetically that separated by special character like comma in asp.net C# [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 3 years ago.
Improve this question
In C#, how can I sort strings that separated by special character, like ","
For example I have string like this
string sStates="IA,KY,CT,ME,AZ";
How can I re-sort them alphabetically like
"AZ,CT,IA,KY"
Split them in an Array will work.
But is there a more effective way?
Thanks in advance for help.
This can be done within a single line of code using linq:
var result = string.Join(",", source.Split(",").OrderBy(s => s));
Efficiency considerations should not apply here unless you're doing this for huge strings (or a hugh number of strings) under a tight timeline, or having an actual performance problem.
Readable code is far better then fast code.
As a rule - You should design your code for clarity, not for performance. Write code that conveys the algorithm it is implementing in the clearest way possible. Set performance goals and measure your code's performance against them. If your code doesn't measure to your performance goals, Find the bottle necks and treat them. Don't go wasting your time on nano-optimizations when you design the code.
You can achieve it in this simple way
var orderedString = source.Split(",").OrderBy(p => p);
var result = string.Join(",", orderedString);
I'm a fan of using Lists in .Net personally.
using System.Linq;
var sStates = "IA,KY,CT,ME,AZ";
var orderedList = sStates.Split(',').ToList().OrderBy(o => o);
var orderedString = string.Join(",", orderedList.ToArray());

Interlocked.Increment at the end of begining of the parallel loop? [closed]

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 8 years ago.
Improve this question
Suppose you have a parallel loop in C# and want to use : Interlocked.Increment
Also, suppose there is a heavy process in your loop. Do you think putting Interlocked.Increment before or after that heavy process might make any difference?
In other words, which of the followings is more preferred?
UPDATE: Suppose our criterion for being better or worse is the overall speed.
Prog1:
int iter = 0;
Parallel.For(...{
HeavyProcess()
Interlocked.Increment(iter);
});
Prog2:
int iter = 0;
Parallel.For(...{
Interlocked.Increment(iter);
HeavyProcess()
});
The "one that is preferred" is simply: the one that is functionally correct. Is it meant to record the number of complete operations (end)? or the number of started operations (beginning). Other than that: no difference.

Methods concatenation in Ruby and C# [closed]

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 8 years ago.
Improve this question
C#:
var articles = Article
.OrderBy(x=> x.Name)
.Where(x=> x.Name.Contains(pattern))
.Select(x=>new {x.Name + " (article)"})
.ToList();
It's good to write this way in C# and it's called "methods concatenation". In fact, I don't remember exactly how they are called, I read it in Jon Skeet's book. The idea is that each method is on a new line, and it's normal in C#.
What about Ruby? Is it normal to write:
articles = Article
.order(:name)
.where("name like ?","%#{pattern}%")
.map(&:name)
.map {|c| c << " (article)"}
Method chaining is a staple in many languages, Ruby included. Its use is largely a matter of personal taste – some, like tokland, don't like the large expressions that can result, whereas I will gladly expand an expression to eliminate temporary variables.
Subjective question, so her's a subjective answer (as Ruby programmer):
I prefer not to create "holes", in my code I wouldn't insert that level of indentation.
You can also insert the dots at the end of the line. Which is more readable? hard to say, I prefer the latter (although I don't mind at the beginning of the line, it's not a big deal). So I'd probably write (note that those two maps could be joined):
article_names = Article.
order(:name).
where("name LIKE ?", "%#{pattern}%").
map(&:name).
map { |name| name + " (article)"}
In my experience, long chains make code harder to follow. When the chain grows too much (5, 6 elements?) I tend to break it creating intermediate variables with meaningful names, this helps me to further describe the expression:
filtered_articles = Article.order(:name).where("name LIKE ?", "%#{pattern}%")
names = filtered_articles.map { |article| "#{article.name} (article)" }

Which code is written better? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I ran a static code analysis tool on our tool and looking at its results the code below was one of the things it was talking about:
SpreadSnapshot oSnap = new SpreadSnapshot();
using (oSnap.SetRowCol(fpSpread, row, col))
{
SpreadSetComboBox(fpSpread, list, displayProperty);
}
So I changed it to the code below and it fixed the error that the tool was talking about:
using (SpreadSnapshot oSnap = new SpreadSnapshot())
{
oSnap.SetRowCol(fpSpread, row, col);
SpreadSetComboBox(fpSpread, list, displayProperty);
}
So in your opinion Which style of coding do you think is more appropriate and less error-prone?
Thanks
The latter - it ensures that you don't end up using oSnap after the using statement.
Aside from anything else, it would be pretty odd for SetRowCol to return something disposable... what would that even mean?
The two mean completely different things, unless SetRowCol returns this at the end. In the first, you're disposing the results of SetRowCol. In the second, you're disposing the SpreadSnapshot.
If both are disposable, you should do a using for both:
using (SpreadSnapshot oSnap = new SpreadSnapshot())
using (oSnap.SetRowCol(fpSpread, row, col))
{
SpreadSetComboBox(fpSpread, list, displayProperty);
}

Categories

Resources