C# equivalent of hasSameSizeAs() - c#

To check that two Iterable have same size, I can write with Java's assertJ
assertThat(elvesRings).hasSameSizeAs(trilogy);
What would be the closest equivalent in C#?
So far I only have
Assert.AreEqual(elvesRings.Count, trilogy.Count);

With the FluentAssertions you can use:
elvesRings.Should().HaveSameCount(trilogy);
Link for library:
https://www.nuget.org/packages/FluentAssertions

The easiest way to do this is to just call count on each IEnumerable<T> (similar to Java's Iterable interface):
Assert.AreEqual(elvesRings.Count(), trilogy.Count());
Notice that Count is called as a method and not a property. This is because when using IEnumerable<T> count is an extension method, and when called with no parameters it simply counts everything within the underlying collection, even if that collection does not have a Count property.
This will work for both MS-TEST and NUnit.

Trivially easy to roll your own extension method to do exactly this, something along the lines of:
public static bool hasSameSizeAs(this IEnumerable first, IEnumerable second)
{
return first.Count() == second.Count();
}
Disclaimer: Error checking, potential multiple iterations of the IEnumerable, etc.

Related

Difference between contains and contains<> in c#

I may be stupid, but what is the difference between contains and contains<> in VS whisper help? Sometimes I get both, sometimes only the one with <>.
They things is that I am trying to use contains in where as in some solutions found here on SO, but it throws error that I best overload method has some invalid arguments (them method is System.Linq.ParallelEnumerable.Contains<TSource>(...)).
My code is like this:
defaultDL = db.SomeEntity
.Where(dl => dl.Something == this.Something
&& (dl.AllLocation == true || this.SomeOtherEntity.Select(loc => loc.Location).Contains(dl.Location)))
.ToList();
If you navigate to definition of System.Linq.Enumerable.Contains method, you will see that it is declared as generic extension method.
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value);
The reason why sometimes it is called with <type> arguments, and sometimes not - is because most of the time compiler will analize it's arguments and determine type automatically. So under the hood, it will be rewritten to explicit generic call.
Like
someCollection.Contains(someValue);
actually is being compiled to
Enumerable.Contains<CollectionInnerType>(someCollection, someValue);
Linq has extension method Contains<>. When you are using it - you can enter type parameters, or not. If you are not enter - c# compiler will try to specify arguments implicitly.
Some other enumerable classes (e.g. List<>) implement own Contain method.
So, when IntelliSense suggest Contains<> method - it is an implementation from Linq; when Contains - it is own implementation of concrete class.
About difference in implementation. Own implementation of class seems to be faster, than Linq implementation, because Linq implementation is more abstract from endpoint class.
There are many possibilities. But here are the most common.
I'm guessing SomeOtherEntity is a reference to an ICollection<T>. That is a standard method on ICollection that scans in memory for reference equality (depending on implementation). You can read about that here.
There also is the Contains<T> which comes from LINQ. It is an extension method. It works on IEnumerable<T> which ICollection<T> is derived from. You can read about this one here.
It has the following basic difference.
Contains is an Extension method while Contains is not.
Contains retrun IEnumerable<T> while Contais return bool value and determines whether your item is present or not. In Contain you can pass deligates that based on condition will return IEnumerable<T>.

is there a .Each() (or .ForEach() ) iterator in the .Net standard library? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
LINQ equivalent of foreach for IEnumerable<T>
I'm wondering whether there is a method for IEnumerable like the following .Each() in the .Net library
var intArray = new [] {1, 2, 3, 4};
intArrary.Each(Console.WriteLine);
I know I can use a foreach loop or easily write an extension method like this:
public static class EnumerableExtensions
{
public static void Each<T>(this IEnumerable<T> enumberable, Action<T> action)
{
foreach (var item in enumberable)
{
action(item);
}
}
}
But I'm hoping not to create my own method to mess up code if there is already such an extension method in the library. And something like .Each() (with a few overloadings which can take conditions as extra params) is heavily needed by programmers, and there should already be one. Am I correct?
Update
Ruby developers may recognize it as a .each() iterator. And that's what I hope to have in C#. Maybe C# can have more iterator methods like those in Ruby.
As others have said there is none built in on IEnumerable<T>. The Linq team was against it as per this post by Eric Lippert::
http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
There is a static method on Array.ForEach and List<T> has an instance method. There is also in PLINQ foreach like statements, but be warned that they work in parallel and can lead to very bad performance for extremely simple actions.
Here is one such method in PLINQ: http://msdn.microsoft.com/en-us/library/dd383744.aspx
And here is a guide on PLINQ in general: http://msdn.microsoft.com/en-us/library/dd460688.aspx
While I can't find the exact article if you poke around in the ParrallelEnumerable section it gives warnings and tips as to how to improve the performance of using parallelism in code
If you want it, I suggest creating 2 versions, one that include indexer and one without. This can be quite useful and can save a select statement to acquire the index.
e.g.
public static void ForEach<T>(IEnumerable<T> enumerable,Action<T> action)
{
foreach(var item in enumerable) action(item);
}
public static void ForEach<T>(IEnumerable<T> enumerable,Action<T,int> action)
{
int index = 0;
foreach(var item in enumerable) action(item,index++);
}
I'd also include argument validation as these are public methods.
Yes there is.
someList.ForEach(x => Console.WriteLine(x));
Or with an array:
Array.ForEach(someArray, x => Console.WriteLine(x));
Note that in this last example you have to call the static method on the Array class
EDIT: The namespaces are: System.Collections.Generic for the List method and System for the Array method
There's a ForEach method on System.Collections.List< T >, but not on IEnumerable. Note, this is also not part of LINQ (it was already there in .NET 2.0).
At first glance you'd expect this to be part of LINQ, as it's sort of an extension on the normal List functionality. However, LINQ is more about grouping, filtering and converting data. If you look closely, most (if not all, I'm not Jon Skeet, I don't know that stuff by heart!) LINQ methods return some sort of IEnumerable.
However, you might want to take a look at MoreLinq. This is an open-source project which adds some key features to the existing LINQ to Objects, one of which is the ForEach method you want (works on any IEnumerable in this case, so it'll work on your array as well).
No, there isn't, unfortunately. (I think this question has been discussed before, but I can't find it currently.)
Due to some bizarre accident of history, the ForEach method ended up on List<T>, instead of IEnumerable<T>, where it would make more sense, and because of backwards-compatiblity, this can never ever be fixed.
Ever since extension methods existed, adding a ForEach(this IEnumerable<T>, ...) extension method was requested over and over again, but it is usually rejected because it would lead to confusing behavior: since instance methods are always selected before extension methods, this would mean that all IEnumerables get treated identically, except for Lists and they wouldn't allow such inconsistencies in the BCL.
As a result, pretty much every .NET project on the planet now starts off with exactly the code you described above:
namespace IEnumerableExtensions
{
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> xs, Action<T> f)
{
foreach (var x in xs) f(x);
}
}
}
Only List<T> provides a ForEach method - for all other types you will have to roll your own extension method.
it depends on the framework version
.net 3.5 and 4.0 have a ForEach method

How to make [example] extension method more generic/functional/efficient?

I needed a double[] split into groups of x elements by stride y returning a List. Pretty basic...a loop and/or some linq and your all set. However, I have not been spending much time on extension methods and this looked like a good candidate for some practice. The naive version returns what I am looking for in my current application....
(A)
public static IList<T[]> Split<T>(this IEnumerable<T> source, int every, int take)
{
/*... throw E if X is insane ...*/
var result = source
.Where ((t, i) => i % every == 0)
.Select((t, i) => source.Skip(i * every).Take(take).ToArray())
.ToList();
return result;
}
...the return type is sort of generic...depending on your definition of generic.
I would think...
(B)
public static IEnumerable<IEnumerable<T>> Split<T>
(this IEnumerable<T> source,int every, int take){/*...*/}
...is a better solution...maybe.
Question(s):
Is (B) preferred ?...Why ?
How would you cast (B) as IList <T[]> ?
Any benefit in refactoring ? possibly
two methods that might be chained or the like.
Is the approach sound ?...or have I
missed something basic.
Comments, opinions and harsh language are always appreciated.
Usage Context: C# .Net 4.0
B is probably the better option. Really the major change is that the consumer of the code has the option to make it a list using ToList() on the end of your method, instead of being forced to deal with a List (an IList, actually, which cannot be iterated).
This has a LOT of advantages in method chaining and general use. It's easy to ToList() an enumerable, but hard to go the other way. So, you can call Select().Split().OrderBy() on a list and use the results in a foreach statement without having to have Linq iterate through the whole thing at once.
Refactoring to yield return single values MIGHT get you a performance bonus, but since you're basically just returning the iterator that the Select gave you (which will yield one item at a time itself) I don't think you'll get much benefit in yielding through it yourself.
I would prefer (B) as it looks more flexible. One way of casting the output of the (B) method to an IList<T[]> is as simple as chaining .Select(x => x.ToArray()).ToList() to it, e.g.,
var foo =
bar.Split(someEvery, someTake).Select(x => x.ToArray()).ToList();
In .Net 4, you can just change the return type to IEnumerable<IEnumerable<T>> and it will work.
Before .Net 4, you would have to cast the internal lists to IEnumerable first, by just calling .Cast<IEnumerable<T>>() on your result before returning.

Simple form of Array class and Enum.GetValues()

I am working with the static method
Enum.GetValues(typeof(SomeEnum));
This method works great when all you need to do is enumerate the values, but for some reason it returns a very simple form of the Array class. I am trying to find an easy way to turn it's return value into a more "normal" collection class like a regular array or List<>.
So far if I want to do that I have to enumerate through the output of Enum.GetValues(typeof(SomeEnum)); and add them one by one to a List<>.
Any ideas how to do this more cleanly?
Answer:
The key is to cast the return result --
SomeEnum[] enums = (SomeEnum[]) Enum.GetValues(typeof(SomeEnum));
If you need a List then jus wrap it in parenthesis and ToList it like so:
List<SomeEnum> list = ((SomeEnum[]) Enum.GetValues(typeof(SomeEnum))).ToList();
If you're using .NET 3.5, you can also use Cast<T> and ToList extension methods.
IEnumerable<SomeEnum> enums = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
You can also get a list if you want to
List<SomeEnum> list = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToList();
Inspired by Jon Skeet's unconstrained-melody, I came up with version I like more:
public static class Enum<T>
where T: struct
{
static Enum()
{
Trace.Assert(typeof(T).IsEnum);
Values = Array.AsReadOnly((T[])Enum.GetValues(typeof(T)));
}
public static readonly ReadOnlyCollection<T> Values;
}
and usage:
var values = Enum<BindingFlags>.Values;
Good thing is this version works faster for multiple calls because it does not create new array on every time.
I found here you can just do this:
SomeEnum[] enums = (SomeEnum[]) Enum.GetValues(typeof(SomeEnum));
And if you need a List just use .ToList() at the end, like this:
List<SomeEnum> list = ((SomeEnum[]) Enum.GetValues(typeof(SomeEnum))).ToList();
Or if you like this better:
List<SomeEnum> list2 = new List<SomeEnum>((SomeEnum[]) Enum.GetValues(typeof(SomeEnum)));
I have a brand new library (UnconstrainedMelody) which helps with this. It can return the values in a strongly typed array or in an immutable list:
SomeEnum[] array = Enums<SomeEnum>.GetValuesArray()
IList<SomeEnum> list = Enums<SomeEnum>.GetValues();
It's generic and has a constraint on the type parameter to make sure it's genuinely an enum. This isn't possible in normal C#, but the library does a bit of furtling to make it work. I like the second form more, because we cache the list - the fact that it's immutable means we can return the same reference again and again.
There are various other utility methods to make it easier to work with flags enums etc.
Enjoy.
This should work:
List<MyEnum> enums = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).ToList();
The reason ToList() didn't work in the solution you posted in your question was that you're missing a set of parens around the casted portion. Hope this helps!
REVISION (12-Sep-2009 ~2:20 PM EST):
So, I made this suggestion last night on the basis that Enum.GetValues returns an Array, and I thought that Array implements IEnumerable<T>:
I believe you can construct a
List<T> passing any IEnumerable<T>
as a parameter into the constructor.
So you should be able to just do this:
List<SomeEnum> values = new List<SomeEnum>(Enum.GetValues(typeof(SomeEnum)));
However, GordonG quite promptly replied to my answer indicating that it doesn't compile. (Ordinarily I would test my answer, but I was at a computer without any development tools at the time and was also feeling quite [unreasonably] sure of myself.)
After some downvotes and heavy soul-searching I resolved to get to the bottom of this matter (after a good night's sleep). Turns out, according to Microsoft's documentation on the Array class here, that Array does implement IEnumerable<T>, but only at run time (so, not at compile time--hence the failure to compile). This, in hindsight, makes sense: Enum.GetValues is not a generic method, and so it cannot know what sort of generic collection to return beforehand. (At least that's how I understand it.)
Anyway, what this all means is that you can legally cast an Array to an IEnumerable<T> provided that you get your type right. And so, at last I can present my final answer, which is really the same as my original answer but with a simple cast thrown in to make everything legal:
// splitting into two lines just for readability's sake
List<SomeEnum> values;
values = new List<SomeEnum>((IEnumerable<T>) Enum.GetValues(typeof(SomeEnum)));
Of course, in retrospect, GordonG wasn't dead set on getting a List<T>, which means his own answer of casting to SomeEnum[] is really just as good.
Updated solution (from 'Konstantin Spirin') for .NET framework 2.0:
public static class Enum<T> where T : struct
{
static Enum()
{
Trace.Assert(typeof(T).IsEnum);
}
public static ReadOnlyCollection<T> Values = new ReadOnlyCollection<T>(((T[])Enum.GetValues(typeof(T))));
}
How about this:
List<SomeEnum> list = new List<SomeEnum>();
foreach (SomeEnum value in Enum.GetValues (typeof (SomeEnum)))
{
if (condition)
list.Add(value);
}

Why is there no ForEach extension method on IEnumerable?

Inspired by another question asking about the missing Zip function:
Why is there no ForEach extension method on the IEnumerable interface? Or anywhere? The only class that gets a ForEach method is List<>. Is there a reason why it's missing, maybe performance?
There is already a foreach statement included in the language that does the job most of the time.
I'd hate to see the following:
list.ForEach( item =>
{
item.DoSomething();
} );
Instead of:
foreach(Item item in list)
{
item.DoSomething();
}
The latter is clearer and easier to read in most situations, although maybe a bit longer to type.
However, I must admit I changed my stance on that issue; a ForEach() extension method would indeed be useful in some situations.
Here are the major differences between the statement and the method:
Type checking: foreach is done at runtime, ForEach() is at compile time (Big Plus!)
The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething);
ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion.
Those are all great points made by many people here and I can see why people are missing the function. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration.
ForEach method was added before LINQ. If you add ForEach extension, it will never be called for List instances because of extension methods constraints. I think the reason it was not added is to not interference with existing one.
However, if you really miss this little nice function, you can roll out your own version
public static void ForEach<T>(
this IEnumerable<T> source,
Action<T> action)
{
foreach (T element in source)
action(element);
}
You could write this extension method:
// Possibly call this "Do"
IEnumerable<T> Apply<T> (this IEnumerable<T> source, Action<T> action)
{
foreach (var e in source)
{
action(e);
yield return e;
}
}
Pros
Allows chaining:
MySequence
.Apply(...)
.Apply(...)
.Apply(...);
Cons
It won't actually do anything until you do something to force iteration. For that reason, it shouldn't be called .ForEach(). You could write .ToList() at the end, or you could write this extension method, too:
// possibly call this "Realize"
IEnumerable<T> Done<T> (this IEnumerable<T> source)
{
foreach (var e in source)
{
// do nothing
;
}
return source;
}
This may be too significant a departure from the shipping C# libraries; readers who are not familiar with your extension methods won't know what to make of your code.
The discussion here gives the answer:
Actually, the specific discussion I witnessed did in fact hinge over functional purity. In an expression, there are frequently assumptions made about not having side-effects. Having ForEach is specifically inviting side-effects rather than just putting up with them. -- Keith Farmer (Partner)
Basically the decision was made to keep the extension methods functionally "pure". A ForEach would encourage side-effects when using the Enumerable extension methods, which was not the intent.
While I agree that it's better to use the built-in foreach construct in most cases, I find the use of this variation on the ForEach<> extension to be a little nicer than having to manage the index in a regular foreach myself:
public static int ForEach<T>(this IEnumerable<T> list, Action<int, T> action)
{
if (action == null) throw new ArgumentNullException("action");
var index = 0;
foreach (var elem in list)
action(index++, elem);
return index;
}
Example
var people = new[] { "Moe", "Curly", "Larry" };
people.ForEach((i, p) => Console.WriteLine("Person #{0} is {1}", i, p));
Would give you:
Person #0 is Moe
Person #1 is Curly
Person #2 is Larry
One workaround is to write .ToList().ForEach(x => ...).
pros
Easy to understand - reader only needs to know what ships with C#, not any additional extension methods.
Syntactic noise is very mild (only adds a little extranious code).
Doesn't usually cost extra memory, since a native .ForEach() would have to realize the whole collection, anyway.
cons
Order of operations isn't ideal. I'd rather realize one element, then act on it, then repeat. This code realizes all elements first, then acts on them each in sequence.
If realizing the list throws an exception, you never get to act on a single element.
If the enumeration is infinite (like the natural numbers), you're out of luck.
I've always wondered that myself, that is why that I always carry this with me:
public static void ForEach<T>(this IEnumerable<T> col, Action<T> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
foreach (var item in col)
{
action(item);
}
}
Nice little extension method.
So there has been a lot of comments about the fact that a ForEach extension method isn't appropriate because it doesn't return a value like the LINQ extension methods. While this is a factual statement, it isn't entirely true.
The LINQ extension methods do all return a value so they can be chained together:
collection.Where(i => i.Name = "hello").Select(i => i.FullName);
However, just because LINQ is implemented using extension methods does not mean that extension methods must be used in the same way and return a value. Writing an extension method to expose common functionality that does not return a value is a perfectly valid use.
The specific arguement about ForEach is that, based on the constraints on extension methods (namely that an extension method will never override an inherited method with the same signature), there may be a situation where the custom extension method is available on all classes that impelement IEnumerable<T> except List<T>. This can cause confusion when the methods start to behave differently depending on whether or not the extension method or the inherit method is being called.
You could use the (chainable, but lazily evaluated) Select, first doing your operation, and then returning identity (or something else if you prefer)
IEnumerable<string> people = new List<string>(){"alica", "bob", "john", "pete"};
people.Select(p => { Console.WriteLine(p); return p; });
You will need to make sure it is still evaluated, either with Count() (the cheapest operation to enumerate afaik) or another operation you needed anyway.
I would love to see it brought in to the standard library though:
static IEnumerable<T> WithLazySideEffect(this IEnumerable<T> src, Action<T> action) {
return src.Select(i => { action(i); return i; } );
}
The above code then becomes people.WithLazySideEffect(p => Console.WriteLine(p)) which is effectively equivalent to foreach, but lazy and chainable.
Note that the MoreLINQ NuGet provides the ForEach extension method you're looking for (as well as a Pipe method which executes the delegate and yields its result). See:
https://www.nuget.org/packages/morelinq
https://code.google.com/p/morelinq/wiki/OperatorsOverview
#Coincoin
The real power of the foreach extension method involves reusability of the Action<> without adding unnecessary methods to your code. Say that you have 10 lists and you want to perform the same logic on them, and a corresponding function doesn't fit into your class and is not reused. Instead of having ten for loops, or a generic function that is obviously a helper that doesn't belong, you can keep all of your logic in one place (the Action<>. So, dozens of lines get replaced with
Action<blah,blah> f = { foo };
List1.ForEach(p => f(p))
List2.ForEach(p => f(p))
etc...
The logic is in one place and you haven't polluted your class.
Most of the LINQ extension methods return results. ForEach does not fit into this pattern as it returns nothing.
If you have F# (which will be in the next version of .NET), you can use
Seq.iter doSomething myIEnumerable
Partially it's because the language designers disagree with it from a philosophical perspective.
Not having (and testing...) a feature is less work than having a feature.
It's not really shorter (there's some passing function cases where it is, but that wouldn't be the primary use).
It's purpose is to have side effects, which isn't what linq is about.
Why have another way to do the same thing as a feature we've already got? (foreach keyword)
https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/
You can use select when you want to return something.
If you don't, you can use ToList first, because you probably don't want to modify anything in the collection.
I wrote a blog post about it:
http://blogs.msdn.com/kirillosenkov/archive/2009/01/31/foreach.aspx
You can vote here if you'd like to see this method in .NET 4.0:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=279093
In 3.5, all the extension methods added to IEnumerable are there for LINQ support (notice that they are defined in the System.Linq.Enumerable class). In this post, I explain why foreach doesn't belong in LINQ:
Existing LINQ extension method similar to Parallel.For?
Is it me or is the List<T>.Foreach pretty much been made obsolete by Linq.
Originally there was
foreach(X x in Y)
where Y simply had to be IEnumerable (Pre 2.0), and implement a GetEnumerator().
If you look at the MSIL generated you can see that it is exactly the same as
IEnumerator<int> enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
int i = enumerator.Current;
Console.WriteLine(i);
}
(See http://alski.net/post/0a-for-foreach-forFirst-forLast0a-0a-.aspx for the MSIL)
Then in DotNet2.0 Generics came along and the List. Foreach has always felt to me to be an implementation of the Vistor pattern, (see Design Patterns by Gamma, Helm, Johnson, Vlissides).
Now of course in 3.5 we can instead use a Lambda to the same effect, for an example try
http://dotnet-developments.blogs.techtarget.com/2008/09/02/iterators-lambda-and-linq-oh-my/
I would like to expand on Aku's answer.
If you want to call a method for the sole purpose of it's side-effect without iterating the whole enumerable first you can use this:
private static IEnumerable<T> ForEach<T>(IEnumerable<T> xs, Action<T> f) {
foreach (var x in xs) {
f(x); yield return x;
}
}
My version an extension method which would allow you to use ForEach on IEnumerable of T
public static class EnumerableExtension
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
source.All(x =>
{
action.Invoke(x);
return true;
});
}
}
No one has yet pointed out that ForEach<T> results in compile time type checking where the foreach keyword is runtime checked.
Having done some refactoring where both methods were used in the code, I favor .ForEach, as I had to hunt down test failures / runtime failures to find the foreach problems.

Categories