Recursive problem - c#

I need compare file names with user input and have to display the files that are matching. I am using a recursive function for that.I stored the matched files in a list.But I got problems when I return the list. How to return values from a function which is called recursively?

You can 'return' data using parameters. For example:
public void MyRecursiveFunction(List<string> files, int depth)
{
files.Add("...");
if (depth < 10)
{
MyRecursiveFunction(files, depth + 1);
}
}

Option 1 (better approach):
You can pass a string to the recursive method, append the filename with a comma to the string inside the recursive function and pass the same string when the recursive function is called from within itself. Better option would be to use a StringBuilder rather than a string.
Option 2 (not recommended):
You might want to declare a global variable have the function append data to it.
In both the options you could use a List<> if more appropriate.

It's trivial; you set an exit case:
function f (List m){
if( y )
{
m.Add(k);
return f(m);
}
return m;
}

Pass the list in as a param. All classes are 'pointers' so when its modified inside the func the changes appears everywhere. If i didnt answer your question heres something i written a few days ago.
oops, this doesnt show passing a list around. However you essentially doing the below but with a list instead of an int? pass the list as a param. Also you can lookup the ref keyword but thats not necessary.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DeleteWhenBelow
{
class Program
{
static void Main(string[] args)
{
var dir = #"C:\Users\FixLoc\Documents\";
var count = findAndDelete(dir, false, 1);
Console.WriteLine(count);
}
static long findAndDelete(string folder, bool recurse, long filesize)
{
long count = 0;
if(recurse)
{
foreach (var d in Directory.GetDirectories(folder))
{
count += findAndDelete(d, recurse, filesize);
}
}
foreach (var f in Directory.GetFiles(folder))
{
var fi = new FileInfo(f);
if (fi.Length < filesize)
{
File.Delete(f);
count++;
}
}
return count;
}
}
}

Since you are using C# 3.0, you could use LINQ to simplify your problem:
var expectedNames = getExpectedFilenames();
var matchingFiles = directoryInfo
.GetFileSystemInfos()
.SelectMany(fsi => fsi.GetFileSystemInfos())
.OfType<FileInfo>()
.Where(fi => expectedNames.Contains(fi.Name));
I have not tested the above code, so it might need some tweaking... The GetFileSystemInfos will get both DirectoryInfo and FileInfo objects, then project the same operation onto each returned entry with SelectMany. SelectMany will flatten the hierarchical structure. OfType filters out directories. The Where searches the set of expected file names against each file name from your projection.

Related

Calling Select inside of List<> extended method in C#

Just wondering why a Select call won't execute if it's called inside of an extended method?
Or is it maybe that I'm thinking Select does one thing, while it's purpose is for something different?
Code Example:
var someList = new List<SomeObject>();
int triggerOn = 5;
/* list gets populated*/
someList.MutateList(triggerOn, "Add something", true);
MutateList method declaration:
public static class ListExtension
{
public static IEnumerable<SomeObject> MutateList(this IEnumerable<SomeObject> objects, int triggerOn, string attachment, bool shouldSkip = false)
{
return objects.Select(obj =>
{
if (obj.ID == triggerOn)
{
if (shouldSkip) shouldSkip = false;
else obj.Name += $" {attachment}";
}
return obj;
});
}
}
The solution without Select works. I'm just doing a foreach instead.
I know that the Select method has a summary saying: "Projects each element of a sequence into a new form." But if that were true, then wouldn't my code example be showing errors?
Solution that I used (Inside of the MutateList method):
foreach(SomeObject obj in objects)
{
if (obj.ID == triggerOn)
{
if (shouldSkip) shouldSkip = false;
else obj.Name += $" {attachment}";
}
});
return objects;
Select uses deferred execution, meaning that it does not actually execute until you try to iterate over the results, with a ForEach, or using Linq methods that require the actual results like ToList or Sum.
Also, it returns an iterator, it does not run on the items in-place, but you're not capturing the return value in your calling code.
For those reasons - I would recommend not using Select to mutate the object in the list. You're just wrapping a ForEach call in a less clean way. I would just use ForEach within the method.

How can I do multiple operations inside a C# LINQ ForEach loop

I have a list of Question objects and I use a ForEach to iterate through the list. For each object I do an .Add to add it into my entity framework and then the database.
List<Question> add = problem.Questions.ToList();
add.ForEach(_obj => _uow.Questions.Add(_obj));
I need to modify each of the objects in the ForEach and set the AssignedDate field to DateTime.Now. Is there a way I can do this inside of the ForEach loop?
You would do something like
add.ForEach(_obj =>
{
_uow.Questions.Add(_obj);
Console.WriteLine("TADA");
});
Have a look at the examples in Action Delegate
The following example demonstrates the use of the Action delegate
to print the contents of a List object. In this example, the Print
method is used to display the contents of the list to the console. In
addition, the C# example also demonstrates the use of anonymous
methods to display the contents to the console. Note that the example
does not explicitly declare an Action variable. Instead, it passes
a reference to a method that takes a single parameter and that does
not return a value to the List.ForEach method, whose single
parameter is an Action delegate. Similarly, in the C# example, an
Action delegate is not explicitly instantiated because the
signature of the anonymous method matches the signature of the
Action delegate that is expected by the List.ForEach method.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");
// Display the contents of the list using the Print method.
names.ForEach(Print);
// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(String name)
{
Console.WriteLine(name);
});
names.ForEach(name =>
{
Console.WriteLine(name);
});
}
private static void Print(string s)
{
Console.WriteLine(s);
}
}
/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/
foreach(var itemToAdd in add)
{
Do_first_thing(itemToAdd);
Do_Second_Thing(itemToAdd);
}
or if you will insist on using the ForEach method on List<>
add.ForEach(itemToAdd =>
{
Do_first_thing(itemToAdd);
Do_Second_Thing(itemToAdd);
});
Personally I'd go with the first, it's clearer.
Most likely you don't need to do things this way. Just use a plain foreach:
foreach (var question in problem.Questions)
{
question.AssignedDate = DateTime.Now;
_uow.Questions.Add(question);
}
Unless there is specific reason to use a lambda, a foreach is cleaner and more readable. As an added bonus it does not force you to materialize the collection of questions into a list, most likely reducing your application's memory footprint.
use a foreach statement
foreach (Question q in add)
{
_uow.Questions.Add(q);
q.AssignedDate = DateTime.Now;
}
or as astander propose do _obj.AssignedDate = DateTime.Now; in the .ForEach( method
Like this
add.ForEach(_obj =>
{
_obj.AssignedDate = DateTime.Now;
_uow.Questions.Add(_obj);
});
add.ForEach(delegate(Question q)
{
// This is anonymous method and you can do what ever you want inside it.
// you can access THE object with q
Console.WriteLine(q);
});

Is there any way to get the list of functions from .cs file?

My manager asked me to get the list of functions available inside each .cs file in our project.
But the number of .cs files are huge.
It is tough to look by manual.
Is there any way to find the function name in .cs files by writing script or code?
Use reflection. If all the files are in the project then you can use:
Type[] types = Assembly.GetExecutingAssembly().GetTypes();
foreach (Type toCheck in toProcess)
{
MemberInfo[] memberInfos = toCheck.GetMembers(BindingFlags.NonPublic | BindingFlags.Public | OtherBindingFlagsYouMayNeed);
//Loop over the membersInfos and do what you need to such as retrieving their names
// and adding them to a file
}
If the project is compiled into a dll then you can use:
Assembly assembly = Assembly.LoadFrom(filePath); //filePath is for the dll
Type[] toProcess = assembly.GetTypes();
//rest of the code is same as above
EDIT:
In case you wanted to find out functions per physical file as #BAF mentions, you would get the base directory for the assembly (through .CodeBase), then do a directory tree walk looking for all .cs files and then you would implement a parser that can distinguish method declarations (might need a lexer as well to help with that) inside each file. There is nothing terribly difficult about either but they do require some work and are too complex to include as an answer here. At lease this is the easiest answer that would cover all types of method declarations that I can think of unless someone can suggest an easier way.
Have you looked at Roslyn?
Check the Get-RoslynInfo script cmdlet by Doug Finke: http://www.dougfinke.com/blog/index.php/2011/10/30/analyze-your-c-source-files-using-powershell-and-the-get-roslyninfo-cmdlet/
Use reflection as mentioned - this will return only the functions which you have made:
Assembly a = Assembly.LoadFile("Insert File Path");
var typesWithMethods = a.GetTypes().Select(x => x.GetMethods(BindingFlags.Public).Where(y => y.ReturnType.Name != "Void" &&
y.Name != "ToString" &&
y.Name != "Equals" &&
y.Name != "GetHashCode" &&
y.Name != "GetType"));
foreach (var assemblyType in typesWithMethods)
{
foreach (var function in assemblyType)
{
//do stuff with method
}
}
You will have a list of types and then within each type, a list of functions.
public class TestType
{
public void Test()
{
}
public string Test2()
{
return "";
}
}
Using the above test type, the code I provide will print Test2 because this is a function. Hope this is what you were looking for.
Edit: Obviously then you can filter to public with the binding flags as mentioned in the other post, using the overload in GetMethods().
If you can't compile the csharp files to assemblies you'll have to write a parser. It is fairly easy to write a regular expression that matches a method declaration (look at the C# language specification). But you will get som false positives (methods declared in block comments), and you also has to consider getters and setters.
If you have one or more assemblies it is quite easy. You can even use System.Reflection from powershell: [System.Reflection.Assembly]::ReflectionOnlyLoad(..). Or you can use Mono.Cecil for assembly examination.
But if you already have the assemblies then use NDepend. You'll get more code information than you need, and they have a free trial.
Do not create something yourself if someone else has already done the hard work.
Since you have the source code, use a tool like Sandcastle which is designed for generating documentation of the source code. You haven't specified what format the output needs to be, so this may or may not be acceptable.
This is something your project/team should be able to do at any time; someone could add a new method or class 5 minutes after you're finished, making your work obsolete.
I have tried with following code please try this one.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace filedetection
{
class Program
{
static void Main(string[] args)
{
string path = #"D:\projects\projectsfortest\BusinessTest";
DirectoryInfo d = new DirectoryInfo(path);//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.cs"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
Program program = new Program();
List<string> allmethord = program.GetAllMethodNames(path+"\\"+file.Name);
foreach (string methord in allmethord)
{
Console.WriteLine(methord);
}
}
Console.ReadKey();
}
public List<string> GetAllMethodNames(string strFileName)
{
List<string> methodNames = new List<string>();
var strMethodLines = File.ReadAllLines(strFileName)
.Where(a => (a.Contains("protected") ||
a.Contains("private") ||
a.Contains("public")) &&
!a.Contains("_") && !a.Contains("class"));
foreach (var item in strMethodLines)
{
if (item.IndexOf("(") != -1)
{
string strTemp = String.Join("", item.Substring(0, item.IndexOf(")")+1).Reverse());
strTemp = String.Join("", strTemp.Substring(0, strTemp.IndexOf(" ")).Reverse());
methodNames.Add(strTemp);
}
}
return methodNames.Distinct().ToList();
}
}
}
In Project Properties, in the Build section, enable XML documentation file. Build your project. The output XML file gives you the list of all classes and their methods, argument names/types, etc.
You can do this with Microsoft.CodeAnalysis.CSharp
The following example should get you going. It assumes you have one class within a namespace:
var output = new List<string>();
var csFilePath = #"C:\File.cs";
var csFileContent = File.ReadAllText(csFilePath);
SyntaxTree tree = CSharpSyntaxTree.ParseText(csFileContent );
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
var nds = (NamespaceDeclarationSyntax)root.Members[0];
var cds = (ClassDeclarationSyntax) nds.Members[0];
foreach(var ds in cds.Members){
//Only take methods into consideration
if(ds is MethodDeclarationSyntax){
var mds = (MethodDeclarationSyntax) ds;
//Method name
var methodName = ((SyntaxToken) mds.Identifier).ValueText;
output.Add(methodName);
}
}

Good lambda expression or better way to reduce for each loop

I want to get sub folders of a root folder. And i am able to get it through the below code.
But has a issue when the sub folder has a sub folder in it and i over come it writing a second for each loop. But what if the second sub folder has a sub folder under it.
So there will be an infinte for each loop, so i have to overcome it.
Any help is worthfull.Thanks in advance.
foreach (Folder.Folder folder in FolderService.Instance.GetSubFolders(userContext, folderID))
{
folderById.Add(folder.FolderID, folder);
foreach (Folder.Folder sfolder in FolderService.Instance.GetSubFolders(userContext, folder.FolderID))
{
folderById.Add(sfolder.FolderID, sfolder);
}
}
Perfect place for recursion:
... TraverseFolder(rootFolderID, userContext)
{
var folderById = new ...;
TraverseFolder(folderById, rootFolderID, userContext);
return folderById;
}
void TraverseFolder(folderById, folderID, userContext)
{
var folders = FolderService.Instance.GetSubFolders(userContext, folderID);
foreach(var folder in folders)
{
folderById.Add(folder.FolderID, folder);
TraverseFolder(folder.FolderID);
}
}
Theoretically, you can have recursive lambdas, but they are waay too complicated.
Is there a good reason for the dictionary to not be at field level rather than passing it through the recursive call?
Dictionary<string, int> folderById = new Dictionary<string,int>();
public void Start()
{
// code for initial context + folder id
RecurseFolders(userContext, folderId);
}
public void RecurseFolders(string userContext, int folderId)
{
foreach (Folder.Folder folder in FolderService.Instance.GetSubFolders(userContext, folderID)) {
folderById.Add(folder.FolderID, folder);
RecurseFolders(userContext, folder.folderId);
}
}
Here are two additional samles using labdas. The first uses a function declared locally to recurse over the items (DirectoryInfos in this case) and the second uses an instance method.
class Program
{
static void Main(string[] args) {
string path = #"d:\temp";
Func<DirectoryInfo, IEnumerable<DirectoryInfo>> func = null;
func = (folder) => {
return new[] { folder }.Concat(folder.GetDirectories().SelectMany(x => func(x)));
};
IEnumerable<DirectoryInfo> dirs = (new DirectoryInfo(path)).GetDirectories().SelectMany(x => func(x));
IEnumerable<DirectoryInfo> dirs2 = GetSubDirs(new DirectoryInfo(path));
}
public static IEnumerable<DirectoryInfo> GetSubDirs(DirectoryInfo dir) {
yield return dir;
foreach (var subDir in GetSubDirs(dir)) yield return subDir;
}
// method 2 even shorter
public static IEnumerable<Directory> GetSubDirs2(DirectoryInfo dir) {
return new[] { dir }.Concat(dir.GetDirectories().SelectMany(x => GetSubDirs2(x)));
}
}
Here is an example how to write recursive traversal using recursive lambda expression and using SelectMany method from LINQ:
Func<string, IEnumerable<string>> folders = null;
folders = s =>
Directory.GetDirectories(s).SelectMany(dir =>
Enumerable.Concat(new[] { dir }, folders(dir)));
foreach (var d in folders("C:\\Tomas\\Writing\\Academic"))
Console.WriteLine(d);
The first line declares the lambda expression in advance, because we use it later inside its definition. This is not a problem, because it will be used after it has been initialized, but the C# compiler requires that we declare it earlier.
The body of the lambda expression calls SelectMany, which calls the given lambda expression for each element of the input sequence and concatenates all returned sequences - our lambda returns the current directory dir and then all recursively calculated subdirectories of dir.
This is probably not particularly efficient, but it definitely shows how you can use lambda functions to write short code (it could be optimized however, F# libraries do that, because this is more common pattern in F#).
Just for comparison, the same thing in F# looks like this:
let folders s = seq {
for dir in Directory.GetDirectories(s)
yield dir
yield! folders dir }
The code uses sequence expressions which are like C# iterators. yield corresponds to yield return and yield! yields all elements of a sequence (it is like iterating over it using foreach and yielding individual elements using yield return, but more efficient).
I got it done . Here's the code.
private List<Folder.Folder> GetAllF(AbstractUserContext userContext, string folderID)
{
List<Folder.Folder> listFold = new List<Folder.Folder>();
foreach (Folder.Folder folder in FolderService.Instance.GetSubFolders(userContext, folderID))
{
listFold.Add(folder);
listFold.AddRange(GetAllF(userContext,folder.FolderID));
}
return listFold;
}

How do you get the index of the current iteration of a foreach loop?

Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?
For instance, I currently do something like this depending on the circumstances:
int i = 0;
foreach (Object o in collection)
{
// ...
i++;
}
Ian Mercer posted a similar solution as this on Phil Haack's blog:
foreach (var item in Model.Select((value, i) => new { i, value }))
{
var value = item.value;
var index = item.i;
}
This gets you the item (item.value) and its index (item.i) by using this overload of LINQ's Select:
the second parameter of the function [inside Select] represents the index of the source element.
The new { i, value } is creating a new anonymous object.
Heap allocations can be avoided by using ValueTuple if you're using C# 7.0 or later:
foreach (var item in Model.Select((value, i) => ( value, i )))
{
var value = item.value;
var index = item.i;
}
You can also eliminate the item. by using automatic destructuring:
foreach (var (value, i) in Model.Select((value, i) => ( value, i )))
{
// Access `value` and `i` directly here.
}
The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.
This Enumerator has a method and a property:
MoveNext()
Current
Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.
The concept of an index is foreign to the concept of enumeration, and cannot be done.
Because of that, most collections are able to be traversed using an indexer and the for loop construct.
I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.
Finally C#7 has a decent syntax for getting an index inside of a foreach loop (i. e. tuples):
foreach (var (item, index) in collection.WithIndex())
{
Debug.WriteLine($"{index}: {item}");
}
A little extension method would be needed:
using System.Collections.Generic;
public static class EnumExtension {
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)
=> self.Select((item, index) => (item, index));
}
Could do something like this:
public static class ForEachExtensions
{
public static void ForEachWithIndex<T>(this IEnumerable<T> enumerable, Action<T, int> handler)
{
int idx = 0;
foreach (T item in enumerable)
handler(item, idx++);
}
}
public class Example
{
public static void Main()
{
string[] values = new[] { "foo", "bar", "baz" };
values.ForEachWithIndex((item, idx) => Console.WriteLine("{0}: {1}", idx, item));
}
}
I disagree with comments that a for loop is a better choice in most cases.
foreach is a useful construct, and not replaceble by a for loop in all circumstances.
For example, if you have a DataReader and loop through all records using a foreach it automatically calls the Dispose method and closes the reader (which can then close the connection automatically). This is therefore safer as it prevents connection leaks even if you forget to close the reader.
(Sure it is good practise to always close readers but the compiler is not going to catch it if you don't - you can't guarantee you have closed all readers but you can make it more likely you won't leak connections by getting in the habit of using foreach.)
There may be other examples of the implicit call of the Dispose method being useful.
Literal Answer -- warning, performance may not be as good as just using an int to track the index. At least it is better than using IndexOf.
You just need to use the indexing overload of Select to wrap each item in the collection with an anonymous object that knows the index. This can be done against anything that implements IEnumerable.
System.Collections.IEnumerable collection = Enumerable.Range(100, 10);
foreach (var o in collection.OfType<object>().Select((x, i) => new {x, i}))
{
Console.WriteLine("{0} {1}", o.i, o.x);
}
Using LINQ, C# 7, and the System.ValueTuple NuGet package, you can do this:
foreach (var (value, index) in collection.Select((v, i)=>(v, i))) {
Console.WriteLine(value + " is at index " + index);
}
You can use the regular foreach construct and be able to access the value and index directly, not as a member of an object, and keeps both fields only in the scope of the loop. For these reasons, I believe this is the best solution if you are able to use C# 7 and System.ValueTuple.
There's nothing wrong with using a counter variable. In fact, whether you use for, foreach while or do, a counter variable must somewhere be declared and incremented.
So use this idiom if you're not sure if you have a suitably-indexed collection:
var i = 0;
foreach (var e in collection) {
// Do stuff with 'e' and 'i'
i++;
}
Else use this one if you know that your indexable collection is O(1) for index access (which it will be for Array and probably for List<T> (the documentation doesn't say), but not necessarily for other types (such as LinkedList)):
// Hope the JIT compiler optimises read of the 'Count' property!
for (var i = 0; i < collection.Count; i++) {
var e = collection[i];
// Do stuff with 'e' and 'i'
}
It should never be necessary to 'manually' operate the IEnumerator by invoking MoveNext() and interrogating Current - foreach is saving you that particular bother ... if you need to skip items, just use a continue in the body of the loop.
And just for completeness, depending on what you were doing with your index (the above constructs offer plenty of flexibility), you might use Parallel LINQ:
// First, filter 'e' based on 'i',
// then apply an action to remaining 'e'
collection
.AsParallel()
.Where((e,i) => /* filter with e,i */)
.ForAll(e => { /* use e, but don't modify it */ });
// Using 'e' and 'i', produce a new collection,
// where each element incorporates 'i'
collection
.AsParallel()
.Select((e, i) => new MyWrapper(e, i));
We use AsParallel() above, because it's 2014 already, and we want to make good use of those multiple cores to speed things up. Further, for 'sequential' LINQ, you only get a ForEach() extension method on List<T> and Array ... and it's not clear that using it is any better than doing a simple foreach, since you are still running single-threaded for uglier syntax.
Using #FlySwat's answer, I came up with this solution:
//var list = new List<int> { 1, 2, 3, 4, 5, 6 }; // Your sample collection
var listEnumerator = list.GetEnumerator(); // Get enumerator
for (var i = 0; listEnumerator.MoveNext() == true; i++)
{
int currentItem = listEnumerator.Current; // Get current item.
//Console.WriteLine("At index {0}, item is {1}", i, currentItem); // Do as you wish with i and currentItem
}
You get the enumerator using GetEnumerator and then you loop using a for loop. However, the trick is to make the loop's condition listEnumerator.MoveNext() == true.
Since the MoveNext method of an enumerator returns true if there is a next element and it can be accessed, making that the loop condition makes the loop stop when we run out of elements to iterate over.
Just add your own index. Keep it simple.
int i = -1;
foreach (var item in Collection)
{
++i;
item.index = i;
}
You could wrap the original enumerator with another that does contain the index information.
foreach (var item in ForEachHelper.WithIndex(collection))
{
Console.Write("Index=" + item.Index);
Console.Write(";Value= " + item.Value);
Console.Write(";IsLast=" + item.IsLast);
Console.WriteLine();
}
Here is the code for the ForEachHelper class.
public static class ForEachHelper
{
public sealed class Item<T>
{
public int Index { get; set; }
public T Value { get; set; }
public bool IsLast { get; set; }
}
public static IEnumerable<Item<T>> WithIndex<T>(IEnumerable<T> enumerable)
{
Item<T> item = null;
foreach (T value in enumerable)
{
Item<T> next = new Item<T>();
next.Index = 0;
next.Value = value;
next.IsLast = false;
if (item != null)
{
next.Index = item.Index + 1;
yield return item;
}
item = next;
}
if (item != null)
{
item.IsLast = true;
yield return item;
}
}
}
Why foreach ?!
The simplest way is using for instead of foreach if you are using List:
for (int i = 0 ; i < myList.Count ; i++)
{
// Do something...
}
Or if you want use foreach:
foreach (string m in myList)
{
// Do something...
}
You can use this to know the index of each loop:
myList.indexOf(m)
Here's a solution I just came up with for this problem
Original code:
int index=0;
foreach (var item in enumerable)
{
blah(item, index); // some code that depends on the index
index++;
}
Updated code
enumerable.ForEach((item, index) => blah(item, index));
Extension Method:
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action)
{
var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void
enumerable.Select((item, i) =>
{
action(item, i);
return unit;
}).ToList();
return pSource;
}
C# 7 finally gives us an elegant way to do this:
static class Extensions
{
public static IEnumerable<(int, T)> Enumerate<T>(
this IEnumerable<T> input,
int start = 0
)
{
int i = start;
foreach (var t in input)
{
yield return (i++, t);
}
}
}
class Program
{
static void Main(string[] args)
{
var s = new string[]
{
"Alpha",
"Bravo",
"Charlie",
"Delta"
};
foreach (var (i, t) in s.Enumerate())
{
Console.WriteLine($"{i}: {t}");
}
}
}
This answer: lobby the C# language team for direct language support.
The leading answer states:
Obviously, the concept of an index is foreign to the concept of
enumeration, and cannot be done.
While this is true of the current C# language version (2020), this is not a conceptual CLR/Language limit, it can be done.
The Microsoft C# language development team could create a new C# language feature, by adding support for a new Interface IIndexedEnumerable
foreach (var item in collection with var index)
{
Console.WriteLine("Iteration {0} has value {1}", index, item);
}
//or, building on #user1414213562's answer
foreach (var (item, index) in collection)
{
Console.WriteLine("Iteration {0} has value {1}", index, item);
}
If foreach () is used and with var index is present, then the compiler expects the item collection to declare IIndexedEnumerable interface. If the interface is absent, the compiler can polyfill wrap the source with an IndexedEnumerable object, which adds in the code for tracking the index.
interface IIndexedEnumerable<T> : IEnumerable<T>
{
//Not index, because sometimes source IEnumerables are transient
public long IterationNumber { get; }
}
Later, the CLR can be updated to have internal index tracking, that is only used if with keyword is specified and the source doesn't directly implement IIndexedEnumerable
Why:
Foreach looks nicer, and in business applications, foreach loops are rarely a performance bottleneck
Foreach can be more efficient on memory. Having a pipeline of functions instead of converting to new collections at each step. Who cares if it uses a few more CPU cycles when there are fewer CPU cache faults and fewer garbage collections?
Requiring the coder to add index-tracking code, spoils the beauty
It's quite easy to implement (please Microsoft) and is backward compatible
While most people here are not Microsoft employees, this is a correct answer, you can lobby Microsoft to add such a feature. You could already build your own iterator with an extension function and use tuples, but Microsoft could sprinkle the syntactic sugar to avoid the extension function
It's only going to work for a List and not any IEnumerable, but in LINQ there's this:
IList<Object> collection = new List<Object> {
new Object(),
new Object(),
new Object(),
};
foreach (Object o in collection)
{
Console.WriteLine(collection.IndexOf(o));
}
Console.ReadLine();
#Jonathan I didn't say it was a great answer, I just said it was just showing it was possible to do what he asked :)
#Graphain I wouldn't expect it to be fast - I'm not entirely sure how it works, it could reiterate through the entire list each time to find a matching object, which would be a helluvalot of compares.
That said, List might keep an index of each object along with the count.
Jonathan seems to have a better idea, if he would elaborate?
It would be better to just keep a count of where you're up to in the foreach though, simpler, and more adaptable.
This is how I do it, which is nice for its simplicity/brevity, but if you're doing a lot in the loop body obj.Value, it is going to get old pretty fast.
foreach(var obj in collection.Select((item, index) => new { Index = index, Value = item }) {
string foo = string.Format("Something[{0}] = {1}", obj.Index, obj.Value);
...
}
int index;
foreach (Object o in collection)
{
index = collection.indexOf(o);
}
This would work for collections supporting IList.
// using foreach loop how to get index number:
foreach (var result in results.Select((value, index) => new { index, value }))
{
// do something
}
Better to use keyword continue safe construction like this
int i=-1;
foreach (Object o in collection)
{
++i;
//...
continue; //<--- safe to call, index will be increased
//...
}
You can write your loop like this:
var s = "ABCDEFG";
foreach (var item in s.GetEnumeratorWithIndex())
{
System.Console.WriteLine("Character: {0}, Position: {1}", item.Value, item.Index);
}
After adding the following struct and extension method.
The struct and extension method encapsulate Enumerable.Select functionality.
public struct ValueWithIndex<T>
{
public readonly T Value;
public readonly int Index;
public ValueWithIndex(T value, int index)
{
this.Value = value;
this.Index = index;
}
public static ValueWithIndex<T> Create(T value, int index)
{
return new ValueWithIndex<T>(value, index);
}
}
public static class ExtensionMethods
{
public static IEnumerable<ValueWithIndex<T>> GetEnumeratorWithIndex<T>(this IEnumerable<T> enumerable)
{
return enumerable.Select(ValueWithIndex<T>.Create);
}
}
If the collection is a list, you can use List.IndexOf, as in:
foreach (Object o in collection)
{
// ...
#collection.IndexOf(o)
}
This way you can use the index and value using LINQ:
ListValues.Select((x, i) => new { Value = x, Index = i }).ToList().ForEach(element =>
{
// element.Index
// element.Value
});
My solution for this problem is an extension method WithIndex(),
http://code.google.com/p/ub-dotnet-utilities/source/browse/trunk/Src/Utilities/Extensions/EnumerableExtensions.cs
Use it like
var list = new List<int> { 1, 2, 3, 4, 5, 6 };
var odd = list.WithIndex().Where(i => (i.Item & 1) == 1);
CollectionAssert.AreEqual(new[] { 0, 2, 4 }, odd.Select(i => i.Index));
CollectionAssert.AreEqual(new[] { 1, 3, 5 }, odd.Select(i => i.Item));
For interest, Phil Haack just wrote an example of this in the context of a Razor Templated Delegate (http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx)
Effectively he writes an extension method which wraps the iteration in an "IteratedItem" class (see below) allowing access to the index as well as the element during iteration.
public class IndexedItem<TModel> {
public IndexedItem(int index, TModel item) {
Index = index;
Item = item;
}
public int Index { get; private set; }
public TModel Item { get; private set; }
}
However, while this would be fine in a non-Razor environment if you are doing a single operation (i.e. one that could be provided as a lambda) it's not going to be a solid replacement of the for/foreach syntax in non-Razor contexts.
I don't think this should be quite efficient, but it works:
#foreach (var banner in Model.MainBanners) {
#Model.MainBanners.IndexOf(banner)
}
I built this in LINQPad:
var listOfNames = new List<string>(){"John","Steve","Anna","Chris"};
var listCount = listOfNames.Count;
var NamesWithCommas = string.Empty;
foreach (var element in listOfNames)
{
NamesWithCommas += element;
if(listOfNames.IndexOf(element) != listCount -1)
{
NamesWithCommas += ", ";
}
}
NamesWithCommas.Dump(); //LINQPad method to write to console.
You could also just use string.join:
var joinResult = string.Join(",", listOfNames);
I don't believe there is a way to get the value of the current iteration of a foreach loop. Counting yourself, seems to be the best way.
May I ask, why you would want to know?
It seems that you would most likley be doing one of three things:
1) Getting the object from the collection, but in this case you already have it.
2) Counting the objects for later post processing...the collections have a Count property that you could make use of.
3) Setting a property on the object based on its order in the loop...although you could easily be setting that when you added the object to the collection.
Unless your collection can return the index of the object via some method, the only way is to use a counter like in your example.
However, when working with indexes, the only reasonable answer to the problem is to use a for loop. Anything else introduces code complexity, not to mention time and space complexity.
I just had this problem, but thinking around the problem in my case gave the best solution, unrelated to the expected solution.
It could be quite a common case, basically, I'm reading from one source list and creating objects based on them in a destination list, however, I have to check whether the source items are valid first and want to return the row of any error. At first-glance, I want to get the index into the enumerator of the object at the Current property, however, as I am copying these elements, I implicitly know the current index anyway from the current destination. Obviously it depends on your destination object, but for me it was a List, and most likely it will implement ICollection.
i.e.
var destinationList = new List<someObject>();
foreach (var item in itemList)
{
var stringArray = item.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
if (stringArray.Length != 2)
{
//use the destinationList Count property to give us the index into the stringArray list
throw new Exception("Item at row " + (destinationList.Count + 1) + " has a problem.");
}
else
{
destinationList.Add(new someObject() { Prop1 = stringArray[0], Prop2 = stringArray[1]});
}
}
Not always applicable, but often enough to be worth mentioning, I think.
Anyway, the point being that sometimes there is a non-obvious solution already in the logic you have...

Categories