Simple foreach, preferred way [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 12 months ago.
Improve this question
I'm accessing some values from the list to populate list of strings in this way
List<string> carNames = null;
foreach (var car in dal.Cars)
{
carNames.Add(car.Name);
}
Is there more efficient way, yet readable to write this? How would you do it?

"Is there a more efficient way"
More efficient is often micro optimization and most times decreases readability. However, one way to optimize performance would be to initialize the list with the correct capacity, which you know already because dal.Cars is also a list:
List<string> carNames = new List<string>(dal.Cars.Count);
carNames.AddRange(dal.Cars.Select(c => c.Name));
Sidenote: i really wonder why microsoft didn't add an overload for ToList/ToArray/ToHashSet which takes the capacity. Then you could use this (Does NOT compile):
List<string> carNames = dal.Cars.Select(c => c.Name).ToList(dal.Cars.Count);

Related

Which of these 3 foreach function's should i use? Where is the difference? [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 2 years ago.
Improve this question
I have 3 foreach function's, writing the list l of type / class Person to Console
foreach(Person p in l)
{
Console.WriteLine(p.first);
Console.WriteLine(p.last);
}
l.ForEach(p =>
{
Console.WriteLine(p.first);
Console.WriteLine(p.last);
});
Parallel.ForEach(l, p =>
{
Console.WriteLine(p.first);
Console.WriteLine(p.last);
});
They are all doing the same except that Parallel is working with threading i guess.
What should i use when?
Here you are using a method that is defined on the List<> class:
l.ForEach(p => { ... });
Internally this uses a for loop to iterate the collection. Use it when you want shorter and more readable code.
A standard foreach provides a bit more control over the loop e.g. breaking out of the loop when a specific condition is met. If want to read more about this just have a look at this article which provides in-depth information about this kind of topic.
Compared to the standard foreach loop, the Parallel.ForEach loop executes in a parallel manner. It uses multiple threads, as you already suggested. Use this when you want to execute multiple processes concurrently. Read more about this here.
Parallel.ForEach(l, p => { ... });

Unit Testing with ForEach [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 7 years ago.
Improve this question
Assuming:
"personList" is a list of Person objects
"agent" is an object that can provide activity about Shop objects (a property of Person)
"GetShopActivity" returns a list of shopping activity objects for a Person
I have this line in a test project:
personList.ForEach(p => new List<Person>(p.Shops)
.ForEach(t=> Assert.IsNotNull(agent.GetShopActivity(t, startDate, endDate))));
How can I make it better?
There is probably a lot you could do, but the first thing to do would be to make it more readable. Perhaps something like this:
var nullActivities =
from p in partnerList
from t in p.Tenants
let activity = agent.GetShopActivity(t, startDate, endDate)
where activity == null
select activity;
Assert.Empty(nullActivities);
Moreover:
you may want to think about
a test should be simple (i.e. it should have a Cyclomatic Complexity of 1).
it should be immediately evident to a person reading the test what scenario and behaviour is being tested (in case the values of startDate and endDate are significant it might be beneficial to give them less generic names).
prefer having only a single assertion as that makes it easy to know where the test failed when it fails.

what is best way to prepare C# objects in separate methods [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
What is better method to use for object preparation logic:
a) with return value
List<Users> users = LoadUsers();
users = PrepareUsers(users);
b) or with void type
List<Users> users = LoadUsers();
PrepareUsers(users)
Are you setting properties on existing User objects or are you creating new ones?
If you're simply changing existing objects, then there's no reason why you'd want to return them, it's redundant. Worse, it's misleading - the client will think his objects were left untouched and that you're creating new objects when in fact you're not.
If you're creating new ones, well then, you obviously need to return them.
Alternative b. since you are working with the same user objects, there is no reason to reassign the variable.

best key, value container where key is string and value is type [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 9 years ago.
Improve this question
What is the suggested key, value container where the key is always of type string, and the value is a type? The container will not be larger than 100 items. Thanks!
You should definitely go with standard Dictionary<TKey, TValue>. The only improvement you can make is based on your there will be no more than 100 items condition.
Use new Dictionary<string, MyType>(int capacity) constructor when creating dictionary, it will prevent underlying storage from reallocating when new items are added.
var dict = new Dictionary<string, MyType>(100);
I have trouble suggesting anything other than the standard .net dictionary if you need concurrency there is also a ConcurrentDictionary

why linq's `except` extension method does not have Except<TSource> Method (IEnumerable<TSource>,HashSet<TSource>) overload? [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 7 years ago.
Improve this question
why linq's except extension method does not have Except<TSource> Method (IEnumerable<TSource>,HashSet<TSource>) overload?
for example
var query = A.Except(B).where(x=>Criteria(x))
foreach(item in query)
{
B.add(item);
DoSomething(item);
}
Given B is HashSet<T>, A is IEnumerable<T> or ICollection<T>
Here in each iteration Except take O(|B|) time.
why there is not a method that just take O(1) time, as B is Hashset anyway.
Update
my crude way is
var query = A.where(x=>!B.contains(x)).where(x=>Criteria(x))
Here in each iteration Except take O(|B|) time
No it doesn't. Except is implemented internally with a collection similar to HashSet<T>. You can have a look at Jon Skeet's proposed implementation in Edulinq. All elements in B are placed in a HashSet<T>, then elements of A are enumerated; if they're not in the HashSet (checking this is a O(1) operation), they are returned in the output sequence.

Categories