Hot answers tagged

22

Use SelectMany. As in, allPersons.SelectMany(s => s);. This flattens the sequence for you.


15

Q&A Is the code readable? ExactlyOne states very clearly what the method is supposed to do. source is null seems odd to me (does that even compile?). I'd prefer source == null. (Edit from comments: a topic about is null vs == null) IEnumerator<TSource> enumerator = source.GetEnumerator() can be written as var enumerator = source.GetEnumerator()....


12

mhmmm... I'm not so sure about this implementation. @dfhwze's points are valid but still, I find it's overengineered. I prefer chaining these two alraedy available extensions that can do all mentioned tricks: return source.Take(2).Count() == 1 or with a predicate return source.Where(predicate).Take(2).Count() == 1;


11

There's certainly room for improvement. Move that that Select(stringFieldFunction).ToList() out of the while loop. Iterating an IEnumerable might be quite expensive, and there's no need to repeat that work when you find a duplicate. Select only those strings that have originalString as a prefix. That will reduce the amount of items you need to check against ...


11

This is for dfhwze as per comment: public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source is null) { throw new ArgumentNullException(nameof(source)); } if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } ...


11

I read it as one long AND operation where the result is the articles that satisfy all the valid predicates. You could therefore build an enumerable of valid predicates in an extension method: public static class ArticleFilterExtensions { public static IEnumerable<Predicate<Article>> GetValidPredicates(this ArticleFiltersModel filter) ...


10

English language These are relatively minor issues, but fixing them might help other people to use / maintain your code. The verb corresponding to permutation is permute. I'm pretty sure that reminder is intended as remainder. Code public static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> source) { return permutate(...


8

I noticed a few things that can be improved: Not all enumerators support Reset. Generator methods don't, for example, so calling ZipNew on the result of a ZipNew call will fail with a NotSupportedException. Obtaining a new enumerator should work, at the cost of having to replace the convenient using statements with try/finally constructions. Edit: As Eric ...


7

public static class Impl { public static IEnumerable<TResult> ZipNew<TFirst, TSecond, TResult>( Names? The class would be more descriptive as something like LinqExtensions; the method something like ZipLooped. using (IEnumerator<TFirst> iterator1 = first.GetEnumerator()) using (IEnumerator<TSecond&...


7

Calling ElementAt inside a loop will cause the IEnumerable to be called multiple times. This code isn't deffering execution either. Now if you think the pervious code wasn't readable then hold on to your hats. I'm going to post some code in hopes someone can build on it and maybe come up with something better. public static class IEnumerableExtensions {...


7

Exit early Instead of stuffing everything in one return statements, return as early as possible. if (!projects.Any()) return Enumerable.Empty<string>(); can be the first statement of your method. It saves recreating the hashset objects and it makes the flow of your method with its recursion more clear. I think sacrificing a bit of "conciseness" for ...


6

I like the second approach since it allows you to exit as soon as a false condition is reached and is simpler than the first. I would offer one minor optimization, keep the check for isletter separate and only check for duplicate if isletter is true: static bool IsIsogram(string str) { //TRICK: HashSet<T>.Add(T) returns false if an item already ...


6

I'm trying to balance the code readability/size with the performance benefits, .. Your code could be optimized for readability and object-oriented design without introducing a performance penalty. The entropy generation could be written more elegantly. original code for (char a = '0'; a <= '9'; a++) { for (char b = '0'; b <= '9'; b++) { ...


6

Using line breaks and {} in code is not a crime :-P Only because we have the nice => doesn't mean we have to use it everywhere. The code is so condensed that it's hard to say where anything begins and ends. I find you should first try to write this function in such a way that it is easy to read and one can see what and where could be optimized. So, I ...


6

public static TSource ArgBy<TSource, TKey>( MinBy and MaxBy are very intelligible names, but ArgBy doesn't say much to me. Really this is a specialised Aggregate (and I wonder whether an implementation using Aggregate might be simpler - or, indeed, whether the existence of Aggregate makes ArgBy unnecessary). Func<(TKey Current, TKey ...


5

Choice of Map Key Ultimately, as you are querying your map based upon the character, you should really make your key as the character. This makes your regular subtraction of 'a' unnecessary. var storeOccurance = new Dictionary<char, bool>(); for (char c = 'a'; c <= 'z'; c++) { storeOccurance[c] = false; } Inconsistent ...


5

If you should respect that not all Enumerators implement Reset() then it is not possible to use using statements for the two IEnumerators. But you could introduce an IEnumerator<TResult> for the zipped result and use it like this: public static IEnumerable<TResult> ZipNew<TFirst, TSecond, TResult>( this IEnumerable<TFirst> first, ...


5

It will be more efficient to call .ToList() just once: // ... var list = enumerableObjects.Select(stringFieldFunction).ToList(); while (list.Any(currentString => string.Equals(currentString, uniqueString, StringComparison.InvariantCultureIgnoreCase))) { uniqueString = originalString + "_" + duplicateCount++; }


5

private string GetUniqueStringForModel<T>( string originalString, IQueryable<T> databaseQueryable, Expression<Func<T, string>> stringFieldFunction ) where T : class { var lowerBound = originalString.ToLowerInvariant(); var upperBound = originalString.ToUpperInvariant() + "z"; var candidates = new HashSet<...


5

You've tagged this linq so you're clearly aware of Linq, but this is not a Linq-like approach. The closest approximation in Linq is GroupBy, so that can serve as a model: Instead of string property take Func<TSource, TKey>. Instead of List<List<T>> (which, apart from anything else, violates the principle of coding to the interface instead ...


5

There are 2 cases for which both your and VisualMelon's implementation can be improved: If count is less than or equal to 0, then you can return source directly. This speeds up iteration by removing an unnecessary intermediate step. For this to work, the yielding part of the method has to be moved into another method, but that's easy with local functions. ...


5

public static IDictionary<string, Dictionary<object, HashSet<T>>> MultiGroupBy<T>(this IEnumerable<T> source, params (string Label, Func<T, object> Getter)[] groupers) I don't understand the mixture of interfaces (IDictionary) and implementations (Dictionary, HashSet), nor the mixture of generics (<T>) and non-...


5

GroupBy vs ToLookup From reference source: Linq Enumerable Dictionary<object, HashSet<T>>> can be replaced with a ILookup<object, T>. public static ILookup<TKey, TSource> ToLookup<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { // impl .. } There is also an ...


5

I would further improve Henrik Hansen's code by throwing away the ifs and integrating the preconditions inside in the queries so they would become: yield articles.Where(article => !filters.IsAvailable.HasValue || article.IsAvailable == filters.IsAvailable); This would not only make it more readable but would show us that now we can actually generate ...


5

where TValue : IComparable<TValue> Don't do this. OrderBy doesn't require its type parameters to implement this interface like this either. Instead it uses the IComparer<T> interface. What's the difference? With IComparable<T>, the implementation of the comparison logic is sitting on the class T itself. This means that there is one and ...


5

var result = new List<ScrapCategory>(); ... if (!result.Contains(parent)) There's one performance problem. Use a data structure which gives fast Contains checks: typically HashSet<>. var parent = categories.Where(x => x.Id == parentId)?.First(); There's another one. I assume that IDs are unique, in which ...


4

Because the LIKE clause has a defined syntax, to do this right (meaning no clause will be incorrectly converted), you will need to use (or create) a simple lexer to parse the LIKE clause. A sample grammar could look like: expr := wild-card + expr | wild-char + expr | escape + expr | string + expr | "" wild-card := % wild-char := ...


4

Branch Complexity While my code works, I feel like it could be improved. Specifically, I don't care for all of the if checks, but I haven't been able to find another way to work it. If you could come up with a smart pattern to reduce the number of if-statements, be my guest. I think some sub patterns can be found, but there would be too many ...


4

You have a lot of code to carefully, almost surgically, merge records from list2 into list1 based on a sorted order. Why not just (1) quickly merge the 2 lists without regards to order, followed immediately by (2) custom ordering? Something short like: mergedList = list1.ToList().Union(list2).ToList(); mergedList = mergedList.OrderBy(x => x.StartTime)....


4

Performance Your code tests against all possible hand result kinds. Is this useful or could you abort whenever you get a match? Is performance an actual requirement anway? public HandResult GetHandResult(int playerID) { IEnumerable<Card> set = GetPlayerSet(playerID).OrderBy(x => x.Face); return new[] { ...


Only top voted, non community-wiki answers of a minimum length are eligible