C# is there a foreach oneliner available? - c#

I just want to know if there is a foreach oneliner in C#, like the if oneliner (exp) ? then : else.

If you're dealing with an array then you can use the built-in static ForEach method:
Array.ForEach(yourArray, x => Console.WriteLine(x));
If you're dealing with a List<T> then you can use the built-in ForEach instance method:
yourList.ForEach(x => Console.WriteLine(x));
There's nothing built-in that'll work against any arbitrary IEnumerable<T> sequence, but it's easy enough to roll your own extension method if you feel that you need it:
yourSequence.ForEach(x => Console.WriteLine(x));
// ...
public static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (T item in source)
{
action(item);
}
}
}

List.ForEach Method

Imagine you have three variables and you want to set the same property of them all in only one go:
foreach (var item in new [] {labelA, labelB, labelC})
{
item.Property= Value;
}
It is the equivalent of doing:
foreach (var item in new List<SomeType>(){labelA, labelB, labelC})
{
item.Property= Value;
}

foreach line-liners could be achieved with LINQ extension methods. For example:
instead of:
var result = new List<string>();
foreach (var item in someCollection)
{
result.Add(item.Title);
}
you could:
var result = someCollection.Select(x => x.Title).ToList();

Sure, you can use something like List<>.ForEach:
List<String> s = new List<string>();
s.Add("This");
s.Add("Is");
s.Add("Some");
s.Add("Data");
s.ForEach(_string => Console.WriteLine(_string));

The primary difference between if and the ?operator is that if is a statement, while ? produces an expression. I.e. you can do this:
var _ = (exp) ? then : else; // ok
but not this:
var _ = if (exp) { then; } else { else; }; // error
So if you are looking for something like a foreach expression, there is no .NET type that can naturally return except for void, but there are no values of void type, so you can equally just write:
foreach (var item in collection) process(item);
In many functional languages, a Unit type is used instead of void which is a type with only one value. You can emulate this in .NET and create your own foreach expression:
class Unit
{
public override bool Equals(object obj)
{
return true;
}
public override int GetHashCode()
{
return 0;
}
}
public static class EnumerableEx
{
public static Unit ForEach<TSource>(
this IEnumerable<TSource> source,
Action<TSource> action)
{
foreach (var item in source)
{
action(item);
}
return new Unit();
}
}
However there hardly exists any use-case for such expressions.

Related

Can I take either string or IEnumerable<T>, where T is string or IEnumerable<T>?

I have a utility method that processes a collection of strings, let's say:
public static string MyJoin(this IEnumerable<string> strings)
{
return string.Join(Environment.NewLine, strings);
}
I'd like to be able to also process IEnumerable<IEnumerable<string>> and IEnumerable<IEnumerable<IEnumerable<string>>> and so on, all of them in this way:
public static string MyJoin(this IEnumerable<IEnumerable<string>> strings)
{
return strings.Select(x => x.MyJoin()).MyJoin();
}
public static string MyJoin(this IEnumerable<IEnumerable<IEnumerable<string>>> strings)
{
return strings.Select(x => x.MyJoin()).MyJoin();
}
Is there any way I can elegantly express this without hardcoding all the possible levels I might want to use?
I've tried to do it with generics, but I just can't figure out the right constraints (if there are any).
I'd also like to avoid declaring a new type, if at all possible.
Performance, on the other hand, is not critical.
Based on Stefan's solution, simplified and compilation-fixed version
public static string MyJoin(this IEnumerable items)
{
if (items is IEnumerable<string>)
{
return string.Join(Environment.NewLine, (IEnumerable<string>)items);
}
if (items is IEnumerable<IEnumerable>)
{
return items.Cast<IEnumerable>().Select(x => x.MyJoin())).MyJoin();
}
throw new InvalidOperationException("Type is not a (nested) enumarable of strings");
}
Be careful with IEnumerable<T> and strings, because a string is an IEnumerable<T>, where T is char.
Static implementation using multiple overloads:
public static string MyJoin(this IEnumerable<IEnumerable<IEnumerable<string>>> items)
{
return items.SelectMany(x => x).MyJoin();
}
public static string MyJoin(this IEnumerable<IEnumerable<string>> items)
{
return items.SelectMany(x => x).MyJoin();
}
public static string MyJoin(this IEnumerable<string> strings)
{
return string.Join(Environment.NewLine, strings);
}
You cannot have a single generic method and "unwrap" the generic argument dynamically.
Implementation using reflection:
public static string MyJoin<T>(this IEnumerable<T> items)
{
if (typeof(T) == typeof(string)
{
return items.Cast<string>().MyStringJoin();
}
var innerIEnumerableType = typeof(T).GetInterfaces().FirstOrDefault(x => x.IsGeneric()
&& x.GetGenericType() == typeof(IEnumerable<>);
if (innerIEnumerableType != null)
{
// create generic method to
var method = typeof(ThisType).GetMethod("MyJoin", /* some flags */)
.MakeGenericMethod(innerIEnumerableType.GetGenericArguments().First())
// recursive call to generic method
return items.Select(x => (string)method.Invoke(null, x)).MyStringJoin();
}
throw new InvalidOperationException("Type is not a (nested) enumarable of strings")
}
public static string MyStringJoin(this IEnumerable<string> strings)
{
return string.Join(Environment.NewLine, strings);
}
To be honest, reflection isn't useful here. Why use generics, if it isn't typesafe anyway? At the end you could just as well use non-generic IEnumerable. It's much easier to implement. See Denis Itskovich's solution, he managed to write down what I actually tried to do.
Rather than having an IEnumerable of an unknown type, what you're really trying to do here is create a tree based structure. The most effective way of doing this is to create a Node class that can represent a value an its children.
public class Node
{
public Node(string value)
{
Value = value;
Children = Enumerable.Empty<Node>();
}
public Node(string value, IEnumerable<Node> children)
{
Value = value;
Children = children;
}
public string Value { get; private set; }
public IEnumerable<Node> Children { get; private set; }
}
This is now a much easier structure to traverse. Here is a general purpose tree traversal method which we can apply to this case:
public static IEnumerable<T> Traverse<T>(T item,
Func<T, IEnumerable<T>> childSelector)
{
var stack = new Stack<T>();
stack.Push(item);
while (stack.Any())
{
var next = stack.Pop();
yield return next;
foreach (var child in childSelector(next))
stack.Push(child);
}
}
var allValues = Traverse(rootNode, node => node.Children)
.Select(node => node.Value);
Partly inspired by Stefan's answer, I've reached a working solution that compiles without generics and (unfortunately) with mostly runtime type checking:
public static string MyJoin(this IEnumerable<string> strings)
{
return string.MyJoin(Environment.NewLine, strings);
}
public static string MyJoin(this IEnumerable<object> items)
{
if (items.All(x => x is string))
return items.Cast<string>().MyJoin();
if (items.All(x => x is IEnumerable<object>))
return items.Cast<IEnumerable<object>>().Select(x => x.MyJoin()).MyJoin();
throw new InvalidOperationException("The argument was not a nested enumerable of strings.");
}
Use the SelectMany extension method.

Edit List contains objects which themselves contain objects, and so on

I have a problem with a List of objects ...
This List contains objects which themselves contain objects, and so on ... (all objects are of the same type)
My objects looks like that :
public class MyObject (...)
{
...
public MyObject[] Object;
...
}
I'd like to change some variables of these objects (according to certain parameters), and to do that I think using LINQ.
My problem is that I do not really know how to do something that will pass through ALL my recursive List, regardless of their level.
I hope I was as clear as possible.
Thank you in advance for your help.
You can write a simple recursive method to do what you want easily enough:
public static void Touch(MyObject obj, string otherParameter)
{
obj.Value = otherParameter;
foreach (var child in obj.Object)
{
Touch(child, otherParameter);
}
}
If you really, really want a more LINQ-esque method, or you do this often enough to need a more generic approach, you could use something like this:
public static IEnumerable<T> FlattenTree<T>(IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
//you could change this to a Queue or any other data structure
//to change the type of traversal from depth first to breath first or whatever
var stack = new Stack<T>();
while (stack.Any())
{
T next = stack.Pop();
yield return next;
foreach (T child in selector(next))
stack.Push(child);
}
}
You could then use it like:
MyObject root = new MyObject();
var allNodes = FlattenTree(new[] { root }, node => node.Object);
foreach (var node in allNodes)
{
node.Value = "value";
}
You could use this recursive extension method:
public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> fnRecurse)
{
foreach (T item in source)
{
yield return item;
IEnumerable<T> seqRecurse = fnRecurse(item);
if (seqRecurse != null)
{
foreach (T itemRecurse in Traverse(seqRecurse, fnRecurse))
{
yield return itemRecurse;
}
}
}
}
You can use it in this way:
var allObj = list.Traverse(o => o.Object);
foreach (MyObject o in allObj)
{
// do something
}
It's handy because it's generic and works with any type and also because it's using deferred execution.
Maybe simply something like this:
static void AddRecursively(MyObject obj, List<MyObject> listToAddTo)
{
listToAddTo.Add(obj);
foreach (var o in obj.Object)
AddRecursively(o, listToAddTo);
}
I suggest to use this extension method that applies an action to all the items recursively
public static void ForEach<T>(this IEnumerable<T> source,
Func<T, IEnumerable<T>> getChildren,
Action<T> action)
{
if (source == null) {
return;
}
foreach (T item in source) {
action(item);
IEnumerable<T> children = getChildren(item);
children.ForEach(getChildren, action);
}
}
You would apply it to your list like this
myObjectList.ForEach(x => x.Object, x => x.Value = "new value");
The first paramter tells ForEach how to access the nested objects. The second parameter tells what to do with each item.

How to check if a type T of a generic method is IEnumerable<> and loop it?

I'd like to do something like this
void DoSomething<T>(T param)
{
if param is IEnumerable<?>
{
loop param and do stuff
}
}
I don't know what to do in the place of the question mark. And is it possible at all?
What you are looking for is :
if (T is IEnumerable) { .. }
but if you expect T to be IEnumerable all the time you can do:
void DoSomething<T>(T param) where T : IEnumerable
{
foreach (var t in param) { ... }
}
or checking the type of the values inside the IEnumerable:
public void DoSomething<T,U>(T val) where T : IEnumerable<U>
{
foreach (U a in val)
{
}
}
Without having to worry to check it yourself, the compiler will do it for you, which is one of the nice things of having a static type system and compiler :)
There are a few ways:
void DoSomething<T>(T param)
{
if (param is IEnumerable)
{
foreach (var item in (IEnumerable)param)
{
// Do something
}
}
}
void DoSomething<T>(T param)
{
if (param is IEnumerable<string>)
{
foreach (var item in (IEnumerable<string>)param)
{
// Do something
}
}
}
void DoSomething<T,TItem>(T param)
{
if (param is IEnumerable<TItem>)
{
foreach (var item in (IEnumerable<TItem>)param)
{
// Do something
}
}
}
You have to check the open generic type of each interface that the class implements, like so:
bool implements = typeof(T).GetInterfaces().Where(t => t.IsGenericType &&
t.GetGenericTypeDefinition() == typeof(IEnumerable<>)).Any();
This will allow you to determine whether or not a type implements IEnumerable<T> without actually knowing what the type T is. Remember that the type can implement IEnumerable<T> multiple times.
If you simply want the sequence of types that are type parameters for IEnumerable<T>, you can change the above query to;
IEnumerable<Type> types = typeof(T).GetInterfaces().
Where(t => t.IsGenericType &&
t.GetGenericTypeDefinition() == typeof(IEnumerable<>)).
Select(t => t.GetGenericArguments()[0]);

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

First, I know there are methods off of the generic List<> class already in the framework do iterate over the List<>.
But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a List<>, and do a Console.WriteLine(object.ToString()) on each object.
Something that takes the List<> as the first argument and the lambda expression as the second argument.
Most of the examples I have seen are done as extension methods or involve LINQ. I'm looking for a plain-old method example.
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
action(item);
}
... and call it thusly:
Each(myList, i => Console.WriteLine(i));
Is this what you're asking for?
int[] numbers = { 1, 2, 3 };
numbers.ToList().ForEach(n => Console.WriteLine(n));
The above could also be written with less code as:
new List<SomeType>(items).ForEach(
i => Console.WriteLine(i)
);
This creates a generic list and populates it with the IEnumerable and then calls the list objects ForEach.
public static void Each<T>(this IEnumerable<T> items, Action<T> action) {
foreach (var item in items) {
action(item);
} }
... and call it thusly:
myList.Each(x => { x.Enabled = false; });
Want to put out there that there is not much to worry about if someone provides an answer as an extension method because an extension method is just a cool way to call an instance method. I understand that you want the answer without using an extension method. Regardless if the method is defined as static, instance or extension - the result is the same.
The code below uses the code from the accepted answer to define an extension method and an instance method and creates a unit test to show the output is the same.
public static class Extensions
{
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
}
[TestFixture]
public class ForEachTests
{
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
private string _extensionOutput;
private void SaveExtensionOutput(string value)
{
_extensionOutput += value;
}
private string _instanceOutput;
private void SaveInstanceOutput(string value)
{
_instanceOutput += value;
}
[Test]
public void Test1()
{
string[] teams = new string[] {"cowboys", "falcons", "browns", "chargers", "rams", "seahawks", "lions", "heat", "blackhawks", "penguins", "pirates"};
Each(teams, SaveInstanceOutput);
teams.Each(SaveExtensionOutput);
Assert.AreEqual(_extensionOutput, _instanceOutput);
}
}
Quite literally, the only thing you need to do to convert an extension method to an instance method is remove the static modifier and the first parameter of the method.
This method
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
becomes
public void Each<T>(Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
You can traverse each string in the list and even you can search in the whole generic using a single statement this makes searching easier.
public static void main(string[] args)
{
List names = new List();
names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);
string stringResult = names.Find( name => name.Equals(“Garima”));
}
Standard:
foreach (Item i in allItems)
{
i.FK_ItemStatus_CustomCodeID = itemStatuses.Where(
x => x.CustomCodeID == i.ItemStatus_CustomCodeID).FirstOrDefault();
}
Lambda:
allItems.ForEach(
i => i.FK_ItemStatus_CustomCodeID =
itemStatuses.Where(
x => x.CustomCodeID == i.ItemStatus_CustomCodeID).FirstOrDefault()
);

C# Code Simplification Query: The Sequential Foreach Loops

Suppose I have some code that looks like this:
foreach(type x in list y)
{
//dostuff1(x)
}
foreach(type x in list y)
{
//dostuff2(x)
}
foreach(type x in list y)
{
//dostuff3(x)
}
foreach(type x in list y)
{
//dostuff4(x)
}
foreach(type x in list y)
{
//dostuff5(x)
}
I cannot combine things into one big for loop like this:
foreach (type x in list y)
{
//dostuff1(x)
//dostuff2(x)
//dostuff3(x)
//dostuff4(x)
//dostuff5(x)
}
Doing so would change the order. Any commentary on the best ways to make the code simpler in C#?
I imagine I could solve this problem by creating a function like this, though I'd rather leave it the way it is than force future readers of my code to understand yield:
void func(type x)
{
dostuff1(x)
yield 0;
dostuff2(x)
yield 0;
dostuff3(x)
yield 0;
dostuff4(x)
yield 0;
dostuff5(x)
yield break;
}
for (int i = 0; i<5; ++i)
{
foreach (type x in list y)
{
//Call func(x) using yield semantics, which I'm not going to look up right now
}
}
Another alternative:
List<Action<Foo>> actions = new List<Action<Foo>> {
doStuff1, doStuff2, doStuff3, doStuff4, doStuff5
};
foreach (Action<Foo> action in actions)
{
foreach (Foo x in list)
{
action(x);
}
}
Just checked, and that works. For instance:
using System;
using System.Collections.Generic;
public class Test
{
static void Main(string[] args)
{
var actions = new List<Action<string>> {
First, Second
};
foreach (var action in actions)
{
foreach (string arg in args)
{
action(arg);
}
}
}
static void First(string x)
{
Console.WriteLine("First: " + x);
}
static void Second(string x)
{
Console.WriteLine("Second: " + x);
}
}
Results of running Test.exe a b c
First: a
First: b
First: c
Second: a
Second: b
Second: c
If you have a fairly constant list of actions, you could just avoid the foreach loops, but still do the actions explicitly (haven't tested the code):
list.ForEach(action1);
list.ForEach(action2);
list.ForEach(action3);
list.ForEach(action4);
Jon Skeet's answer is excellent (I just voted it up). Here's an idea to take it one step further:
If you do this a lot, you could make an extension method called "DoActionsInOrder" (or maybe you can come up with a better name) that does this. Here's the idea:
public static void DoActionsInOrder<T>(this IEnumerable<T> stream, params Action<T> actionList)
{
foreach(var action in actionList)
{
foreach(var item in stream)
{
action(item);
}
}
}
Then, you could call it like this:
myList.DoActionsInOrder(doStuff1, doStuff2, doStuff3, doStuff4, doStuff5);
How about:
interface IDoStuff
{
void DoStuff(x);
}
List<IDoStuff> listOfActions = ...
foreach (IDoStuff iDoStuff in listOfActions)
{
foreach (type x in list y)
{
iDoStuff(x);
}
}
[edit] And yes, you should rather go for the generic solution as J.Skeet said (although you can use a generic interface instead of a delegate as well).
If you must retain the sequential nature, there's not much you can do. You could do some extension method shortcuts, but IMHO this makes for less readable code. Also, you may run into problems depending on your method signatures.
You could refactor to move the iteration to separate functions.
// Method 1
DoStuff1ToList(y);
DoStuff2ToList(y);
DoStuff3ToList(y);
DoStuff4ToList(y);
DoStuff5ToList(y);
// Do Stuff 1
foreach (var x in y)
{
// do actual stuff
}
i think this is the same as testing.ForEach(action)
so just use that if your going down this kind of route.
private static void DoDifferentStuffToThings()
{
List<string> testing = new List<string>() { "hello", "world" };
Action<string> action1 = (a) =>
{
Console.WriteLine("Action 1 {0}", a);
};
Action<string> action2 = (a) =>
{
Console.WriteLine("Action 2 {0}", a);
};
DoStuffToThings<string>(testing, action1);
DoStuffToThings<string>(testing, action2);
}
private static void DoStuffToThings<T>(IEnumerable<T> list, Action<T> dothing)
where T : class
{
foreach (var item in list)
{
dothing(item);
}
}

Categories