# Tag Info

## Hot answers tagged extension-methods

32

If you're using C# 6.0, I believe you can drop the null-check: public static string WithMaxLength(this string value, int maxLength) { return value?.Substring(0, Math.Min(value.Length, maxLength)); } Other than that, it's like Jeroen said: that's pretty much as good as it gets. The class and parameter naming is exactly as I'd have it, and the name of ...

31

Why didn't Microsoft include this in the .NET framework? Probably because it can be realized in one line with Select: source.Select(x => x.Equals(oldValue) ? newValue : x) or with 2 lines as extension method if the function is needed frequently. public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T ...

25

I cannot comment about the speed because I didn't benchmark it but there are two obvious improvements. add an IEqualityComparer<T> as a third parameter so that you can use a custom one if necessary (e.g. own typs) use foreach instead of the enumerator Example: public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T ...

25

Parallel computing and asynchonous computing are two separate things. While they might be similar in some cases, the two terms have two very distinct meanings in C#-land: Asynchronous computing is used for the async/await and Task<T> idioms. Parallel computing is what you are doing here, using plinq: processing streams of data in different threads in ...

18

So Apple already has an implementation for this, using NSNumberFormatter. A bit easier to implement than what you have now ;). var numberFormatter:NSNumberFormatter = NSNumberFormatter() numberFormatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle var string = numberFormatter.stringFromNumber(100)

17

With regex it's virtually a one-liner: var words = Regex.Matches("SmallFireBall", @"([A-Z][a-z]+)") .Cast<Match>() .Select(m => m.Value); var withSpaces = string.Join(" ", words); Regex.Matches - searches an input string for all occurrences of a regular expression and returns all the matches. MSDN [A-Z][a-z]+ - matches strings that ...

15

I'm pretty sure there's no better way to do this but I thought a consensus on here might be nice. Let me know what you think. At first glance it seems to be ok but one could assume that he/she is always getting either the value or the default value. If one would get the default value for e.g if the dictionary is empty, why shouldn't he/she get the default ...

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()....

15

Understanding your code was a bit of a challenge (albeit an interesting one). Overall, I see a lot of function definitions that don't seem to accomplish anything. Why did you write public static IOrderedEnumerable<Pair> SortPairs(this IEnumerable<Pair> data) => data.OrderBy(p => p.Key); and then write .SortPairs() when you could have ...

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

My personal view is create an extension method if: The class/interface you wish to extend is not created by you. The class/interface is created by you but the behavior of the extension method is only required in an assembly that doesn't contain the class (e.g. class Person is defined in MyApp.dll, but GetAge() is only required in MyApp.UI.exe). The behavior ...

11

I would change your method to use generics (so that the return value is meaningful) and not call .ToString() internally. This will enable you to use it in more scenarios. public static T GetValueTernary<T>(this HtmlHelper html, object a, object b, T valueIfEqual, T valueIfNotEqual) { return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual; } ...

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

While your goals may be admirable, I think that, when performance takes a large hit, the whole approach needs to be re-examined. This is atleast 5X's slower than a comparable one liner, even after removing the Combine() method and just returning an IEnumerable<string>. If someone wanted to test with different terms(ie 7 and 9) and/or different words(...

10

A shorter form of Trevor's answer (but essentially doing the same thing): public static IEnumerable<T> Circle<T>(this IEnumerable<T> list, int startIndex) { return list.Skip(startIndex).Concat(list.Take(startIndex)); } This will still lazy evaluate just like Trevor's answer, because Concat lazily evaluates. Further more, if you have ...

10

Your code will throw an exception when a is null. A safe way to compare values is the static version of object.Equals(): object.Equals(a, b)

10

There is an inconsistency - negative values of maxLength would be forgiven for value being null, but cause an exception for every other input (since Substring would throw an ArgumentOutOfRangeException). There's two possible approaches that remove this inconsistency - fail fast public static string WithMaxLength(this string value, int maxLength) { if (...

10

This is not so much of a code answer as a mathematical answer. We can calculate directly the number of multiples $m$ of a natural number $n$ that are below the limit $x$. It's simply $\lceil x/n\rceil$. The sum of those multiples is: $$n\sum_{i=1}^{\lceil x/n\rceil}= n\left(\frac{1}{2}(\lceil x/n \rceil)(\lceil x/n\rceil+1)\right)$$ So for $n=3$ ...

10

You should be able to cut the code length and improve performance, by simplifying the algorithm. Here are some of the problems I've noticed in your implementation: You're currently processing all of the type's properties, this is not necessary as you only need few concrete ones. There are few other problems deriving from this one. You're creating the ...

10

Review You use very clean and strong names for all your variables so it's very easy to understand your code. You too often go without {}. Especially the double for loops become very confusing. You don't use good exception messages. In Arg_SeparatorEnumIllegalVal the Arg prefix is not necessary because the type of the exctpion is already telling me it's ...

10

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&...

10

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 ...

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(...

9

Edge cases: ";abc".LazySplit(";") will return an empty sequence. To match the behaviour of ";abc".Split(new char[] { ';' }) it should return the sequence { "", "abc" }. ";abc".LazySplit("") will return a sequence with a single item, the empty string. To match the behaviour of ";abc".Split(new char[] { }) it should return the sequence { ";abc" }. Here's how ...

9

Can you not simply do SequenceEqual? var list = new List<string> { "test1", "test2", "test3" }; var list2 = new List<string> { "test1", "test2", "test3" }; var areListsEqual = list.SequenceEqual(list2);

9

Sanitizer is a dangerous misnommer IMO. A better name could be NameQuoter, since that's what it does: it uses the RDBMS-specific syntax for quoting identifiers - SQL Server using square brackets, MySQL using backticks, Oracle using backslashes: this has nothing to do with sanitizing, which from what I can tell is essentially impossible to achieve with this ...

9

There are not much to review, so to answer your questions: It's a good extension if you can see it useful in more than one place. It makes sense. I can't see anything else to consider - a null check on the predicate maybe? If the exception thrown by the predicate when @this is null is good enough for you, don't bother further. I don't see why the ...

9

The comments mention being reusable as the main goal of the code. It is however far from it. The main issues I see with most of the extension methods above: Looking at the name of the methods (and parameters) I can't always tell what the outcome will be. When the outcome is pretty clear, the implementation reveals surprinzing, totally unexpected side-...

9

Now, I fully congratulate you on the exercise - it's an interesting problem and I think a great learning opportunity. However, to learn from this we must acknowledge it's shortcomings. I think the biggest, most glaring issue for me is that this decomposes business logic beyond the simplest possible implementation! Take a second and look at these three ...

8

There are a few things I notice right off the bat. Your variable names while not bad, could be better. For instance props -> properties. Stuff like this makes the code easier to read. You have the properties, why not use a foreach loop to fill the datatable (you did it in ToDataSet) the _ prefex should be used for class variables, not local variables. try ...

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