FAQ Database Discussion Community


Why does this string extension method not throw an exception?

c#,null,comparison,ienumerable,argumentnullexception
I've got a C# string extension method that should return an IEnumerable<int> of all the indexes of a substring within a string. It works perfectly for its intended purpose and the expected results are returned (as proven by one of my tests, although not the one below), but another unit...

Get an enumerator for the implemented interface from a class array

c#,ienumerable
I have such a function sealed class AssignedTasks : IReadonlyAssignedTasks { ... } interface IReadonlyAssigningInfo : IEnumerable<IReadonlyAssignedTasks> {} sealed class AssigningInfo : IReadonlyAssigningInfo { private readonly AssignedTasks[] _assignedTasks; ... public IEnumerator<IReadonlyAssignedTasks> GetEnumerator() { return _assignedTasks.GetEnumerator(); } } I have error Cannot implicitly convert type 'System.Collections.IEnumerator' to 'System.Collections.Generic.IEnumerator'. An explicit conversion...

To ToList() or not to ToList()?

c#,performance,linq,ienumerable,tolist
Given an in memory (not LINQ to SQL) list of classes: List<MyClass> myItems = /*lots and lots of items*/; which I am grouping using a GroupBy() statement: myItems.GroupBy(g => g.Ref) and then immediately consuming in a foreach loop is there any difference in calling .ToList() on the "group" or should...

Setting an empty list of type object to a function that returns IEnumerable of type object

c#,linq,list,ienumerable
In my BLL I need to first declare an empty list and then eventually set it later in the code using a function from my DAL that returns type IEnumerable. Is this the proper way to do something like this? IEnumerable<productList> productList = new List<Product>(); productList = DAL.GetProducts(); Normally I...

Enumerable.Where() not possible on IEnumerable?

c#,linq,ienumerable
I have an XmlNodeList and want to call the .Where() to get a filtered Node-List. But this doesn't work. Now I'm wondering, why sometimes the .Where() works and sometimes not. How could I get this code running with the .Where() ? XmlDocument doc = new XmlDocument(); doc.LoadXml(Xml); var oTestNodes =...

How to create an HtmlHelper extension method that will bind an IEnumerable to a table

asp.net-mvc,html-table,ienumerable,model-binding
This is my view model: public class TaskViewModel{ public int TaskID{get;set;} public IEnumerable<TaskExecutor> Executors{get;set;} } public class TaskExecutor{ public int ExecutorID{get;set;} public string LastName{get;set;} public string FirstName{get;set;} } In my view I have done something like this: <table> @foreach(var item in Model.Executors) { <tr> <td>item.ExecutorID</td> <td>@string.Format("{0} {1}",item.FirstName,item.LastName)</td> </tr> } </table>...

Easiest method to OrderBy a String using StringComparison.Ordinal

c#,string,compare,ienumerable,ordinal
I've found a bug (in my code) that results from String.CompareTo and binary search because my custom IComparer (for the wrapping type) uses String.Compare(x, y, StringComparison.Ordinal). This is because items.OrderBy(i => i.Name) (where Name is of type string) used to build the Array to search used the string object itself...

Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable

c#,list,ienumerable
public IEnumerable<Products_Products> getprod() { var db = new Model.atengturonDBEntities(); IEnumerable<Products_Products> x = new List<Products_Products>(); var test = (from name in db.Products_Products select name.ProductName).ToList(); x = test; return x; } why am I getting this error? I also tried to change all 'IEnumerable' to 'List', Help me! thanks :) Cannot implicitly...

Split a collection into n parts with LINQ, in VB.Net

.net,vb.net,linq,ienumerable
Question In VB.Net, If I have a collection like this: Dim collection As IEnumerable(Of Integer) = Enumerable.Range(0, 99) How I could split it in groups/Ienumerables of an indeterminated amount of elements? Conditions Using a LINQ query (not MORELinq or any other 3rd party libs) Not writting a Function, just using...

Trouble combining Linq Expressions into a Func

linq,nhibernate,ienumerable,iqueryable
I've been trying to factor some common lambda subexpressions out into reusable components and have hit a wall. I'll show what I've done so far with a simplified example and hope one of you can shed some light. My subexpressions are ultimately used in an NHibernate Query (IQueryable interface). Here's...

Getting words out of a text file with C#

c#,text-files,ienumerable,yield-return
I want to apologize for my beginner mistakes and english. I have write a method that gets words that start with a "b" out of a randomtext file and return a IEnumerable. It has to work with a yield return. The problem is that i don't know how to write...

How to concat async enumerables?

c#,asynchronous,async-await,ienumerable
I have a method with this return type: public async Task<IEnumerable<T>> GetAll() It makes some further async calls (unknown number) each of which return a task of enumerable T, and then wants to concat the results for the return. var data1 = src1.GetAll(); var data2 = src2.GetAll(); var data3 =...

Error: IEnumerable could Not be defined in non-generic static class

c#,generics,compiler-errors,ienumerable
The class with IEnumerable interface got an error when complied. Extension method must be defined in a non-generic static class Please help on that. I do not want the class be static, that will cause much more error(something can not be defined in static class). Thanks a lot! namespace phyl...

counting occurances of item in IEnumerable using linq in C# [duplicate]

c#,linq,ienumerable
This question already has an answer here: Find the most occurrence of a character in string C#? 8 answers I'm trying to find a clever way using linq to examine an IEnumerable and find the max occurrences of some element. "aba".SomeLinqExpression(); // => 'a' or (new List<int>{1, 2, 3,...

Why is it.current changing his values during debug?

c#,iterator,ienumerable,enumerator
I'm trying to get an element at a specific index with the method : public T GetElem(int index) { var it = outerInstance.iterator(); var i = 0; while (it.MoveNext() && i < index) { i++; } return it.Current; } I have created my own iterator which is an internal class...

Could not find an implementation of the query pattern for souce type

c#,linq,ienumerable
I am a beginner so please bare with me and my english. I am trying to print and get a row of numbers(2,4,8,16, 32, ) but then is should be greater than 10 but smaller than 1000 with LINQ expressions. I don't know what i am doing wrong. The error...

Order by names starting by searched string alphabetically LINQ

c#,linq,sorting,ienumerable
I have following data jabb Bucynski Bartley Abart Benson Brown Beerbower Mack Nina Salt Walter User performs search on these records, I want to sort records in such a way that records starting with search string should appear on top in alphabetical order and the remaining records should come after...

Why is an IEnumerable(or IList) implemented using arrays instead of Linked Lists?

c#,arrays,data-structures,ienumerable
I was reading basic tutorials on implementing the methods of the interface IENumerable and found out that all examples use arrays. I was under the impression that an IENumerable is essentially very similar to a linked list. And I am fairly confident that an array and a linked list are...

Entity Framework - Should I edit an object in a function, or after a function completes

asynchronous,asp.net-mvc-5,entity-framework-6,ienumerable,updatemodel
I am coding a MVC 5 internet application, where I retrieve many Account objects that need emails sent to, then I send the emails. After the emails have been sent, I need to update a DateTime field in each Account object to store a value to show that the email...

Display List return from a controller to a table in view ASP.NET MVC4

asp.net-mvc,asp.net-mvc-4,ienumerable
I have a function in my controller class, it return a list of data, i want to display it in table structure in my view page. i had tried the following code but it shows some error "Class does not contain definition of GetEnumerator" Controller public ActionResult data(Message msg,IEnumerable<sample> dept)...

While loop returning AFTER exit (IEnumerable involved) causing bounds error

c#,loops,search,ienumerable
I know there are many ways to skin this cat, but I'm having some issues with a basic while loop that exits properly, but returns (and increases the counter) upon returning an IEnumerable.ToList() from the parent function. Basically what I'm trying to do is search a list of individual keywords...

Converting IEnumerable to Dictionary

c#,dictionary,casting,ienumerable,deferred-execution
after adding bool distinct to method Splitter and checking if distinct is true the code broke. The quesry now instead of being dictionary is IEnumerable<string>, but whould be Dictionary<string, int>. How could it be solved? This is the error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.Dictionary'. An explicit conversion exists...

Iterating over IEnumerable using foreach skips some elements

c#,ienumerable
I've faced with difference in behavior between iterating over enumerable and over enumerable.ToList(). public static void Kill(Point location) { Wound(location); foreach(var point in GetShipPointsAndTheirNeighbors(location).ToList()) { CellsWithShips[point.X, point.Y] = false; } } /// <summary> /// This version does not work for strange reasons, it just skips a half of points. See...

Simple IEnumerable class definition [closed]

c#,.net,ienumerable
I saw an answer to my question on this forum but I've been looking for an hour today and I cant find it anymore. I need to create a simple class with only 2 properties that will follow IEnumerable interface with yield return in enumerator that would return each of...

How to group items in a list with the same max date and filter them

c#,.net,linq,list,ienumerable
I have List<TakenBMI> with these 4 columns and data: TakenDate UerID TakenItem TakenValue Aug-10-2014 34 Weight 140 Aug-10-2014 34 Height 5.5 Mar-15-2015 34 Weight 141 Mar-15-2015 34 Height 5.5 I want to group them in separate lists based on the TakenDate and find out which list I should use that...

Select the first object that match condition or an inner object

c#,lambda,ienumerable
I have a class that contains an inner list of the same class, For example: class Foo { string SearchId; List<Foo> GroupedPackages } I want to return the first "foo" instance that fits a condition, it can be in the main instance or in the inner List. This is what...

“Left XOR” between two lists with LINQ

c#,linq,ienumerable
I have to collections: IEnumerable<lineResult> diplayedBondsList and List<string> pIsinList lineResult is a very simple class defined as: public class lineResult { public string isin { get ; set ; } public double rate { get ; set ; } public string issuer { get ; set ; } } I...

Iterate over IEnumerable stops after first iteration

c#,ienumerable,ienumerator
I have the following in my Main() method Reeks r = new Reeks(); foreach(int i in r){ if(i < 1000){ Console.WriteLine(i); } } What i want is to iterate over a Reeks until the value of i > 1000 where i is the previous value multiplied by 2, ie [1,2,4,8,16,32]....

Why is the error handling for IEnumerator.Current different from IEnumerator.Current?

c#,ienumerable
I would have thought that executing the following code for an empty collection that implements IEnumerable<T> would throw an exception: var enumerator = collection.GetEnumerator(); enumerator.MoveNext(); var type = enumerator.Current.GetType(); // Surely should throw? Because the collection is empty, then accessing IEnumerator.Current is invalid, and I would have expected an exception....

Enumerate all controls in a form (redundant)

vb.net,ienumerable,redundancy
I'm trying to enumerate all the controls in a form that satisfy a certain condition like the code beelow Public Enum MethodSeachEnum StartsWith = 1 EndsWith = 2 Contains = 3 End Enum Public Function GetAllControls(Control As Control, Key As String, MethodSeach As MethodSeachEnum, ControlType As Type, Optional UseTag As...

In which cases do I need to create two different extension methods for IEnumerable and IQueryable?

c#,.net,linq,ienumerable,iqueryable
Let's say I need an extension method which selects required properties from the collection. This can be entity or .net collection. So I have defined such extension method: public IQueryable<TResult> SelectDynamic<TResult>( this IQueryable<T> source, ...) This works fine for IQueryables. But, I also need to call this function for IEnumerables....

How efficient is IEnumerable.First and IEnumerable.Last?

.net,linq,queue,ienumerable,peek
I want to use a System.Collections.Generic.Queue, but with one difference: I want Queue.Peek to return the last item put in rather than the first. I still want items to enter and exit in the same manner. I was thinking of using Queue.Last() as an alternative to Queue.Peek() (which I assume...

PropertyInfo.GetValue(object) fails with IEnumerable [C#, Reflection]

c#,reflection,ienumerable,var-dump,propertyinfo
I have the following problem: I am currently writing the c# equivalent of PHP's var_dump-method. It works perfectly with 'simple' classes and structures (and even with arrays). My only problem is when it comes to other IEnumerable<T>, like List<T> etc: The debugger is throwing an TargetParameterCountException. My code looks as...

C# IEnumerable equivalent of next() method of java Iterator?

java,c#,iterator,ienumerable
I found (here)a sort of implementation of an Iterator in c# that mimics Java's Iterator methods but I'm not quite sure how to use it in my case or if there's an easier option to rewrite this method c#'s way. Original java method: public RWIterator<T> search (T e){ RWIterator<T> it...

Accessing IEnumerable clears content

c#,cassandra,ienumerable
I've got a database (Cassandra) query that returns an IEnumerable. Trying to track down why this was returning no data (when I know there's data in the database) I found a curious issue. The query does in fact return data, 25 entries. I was checking this with a Data.Count(); But...

Item from IEnumerable changed inside foreach, but change not saved to collection

c#,ienumerable
I had an interesting problem today, this is a reproduction: class TestListAndEnumerable { public static void Test() { bool b1 = GetBool1(); // returns false bool b2 = GetBool2(); // returns true } private static bool GetBool1() { IEnumerable<BoolContainer> list = new List<bool> { false }.Select(x => new BoolContainer {...

Missing directory and file info

c#,ienumerable,enumerate,directoryinfo,filesysteminfo
The following is not returning a full list of files and directories: IEnumerable<FileSystemInfo> files = new DirectoryInfo("C:\\Windows\\System32\\drivers").EnumerateFileSystemInfos("*", SearchOption.AllDirectories); The application is run as a administrator. There are no additional file filter drivers in place. For example if I run: foreach (FileSystemInfo file in files) { Console.WriteLine(file.Name); } I get: en-US...

Implementing IEnumerable, Lists

c#,list,ienumerable
I found this MSDN tutorial It describes implementing IEnumerable in order to use the object in a foreach loop. My question is, in the example's main method it uses a Person array to initialize the People class. Can I use a List< ClientEntry> rather than an array of ClientEntry? What...

C# repeating IEnumerable multiple times

c#,ienumerable
How to repeat whole IEnumerable multiple times? Similar to Python: > print ['x', 'y'] * 3 ['x', 'y', 'x', 'y', 'x', 'y'] ...

GetEnumerator does not exist in this context

c#,linked-list,ienumerable,ienumerator
I have implemented a custom linked list and I am having trouble implementing the IEnumerator<>. Specifically, the compiler tells me The name "GetEnumerator" does not exist in the current context. I feel like I'm implementing it exactly how I have seen in numerous stackoverflow posts and tutorials, what am I...

C# pass generic type as a generic type parameter?

c#,generics,ienumerable
public static C RotateLeft<C, T>(C list, int count) where C : IEnumerable<T> { return list.Skip (count).Concat(list.Take(count)); } I want to achive something like this, where T is a type paramter to IEnumerable, and C implements IEnumerable. This is the syntax I came up with but it does not pass the...

IEnumerable Group By user specified dynamic list of keys

c#,.net,asp.net-mvc,lambda,ienumerable
I have a class like public class Empolyee { public string Designation {get ;set;} public string Discipline {get ;set;} public int Scale {get ;set;} public DateTime DOB {get ;set;} public int Sales {get ;set;} } and have records of all employees in an enumerable say List<Employee> Employees; and a list...

How to detect enum type passed to Enum[]

c#,enums,ienumerable
In my MVC project I have MyEnum: public enum MyEnum { a, b, c, d } I also have class: public class MyClass { public MyEnum SelectType { get; set; } public Enum[] NotSupportedTypes{ get; set; } } In my class for NotSupportedTypes I can use only Enum[] type. When...

Creating an extension method to wrap types as IEnumerables

c#,generics,extension-methods,ienumerable
I wanted to create an extension method that would efficiently wrap single objects as IEnumerables. This was to avoid the cases where you end up putting a new [] {} in the middle of an expression. This is easy enough to do using the following method: public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this...

Convert dictionary with List to IEnumerable

c#,dictionary,ienumerable
I have a dictionary: Dictionary<String, List<Foo>> test = new Dictionary<String, List<Foo>>(); I then populate this dictionary hence why I need the list so I can call Add(). My problem is the function needs to return: Dictionary<String, IEnumerable<Foo>> Is there any easy way to do this without doing the obvious and...

Lazy initialization confusion

.net,vb.net,collections,ienumerable,lazy-initialization
Scenario I'm trying to read the resources contained in a .Net managed resource file, a ResX file. I've designed this simple class that will serve me to store/struct a collection of resources: Public Class Resource Public Property Name As String Public Property Data As Object Public ReadOnly Property Type As...

Looping through an enum, TypeScript and JQuery

jquery,enums,typescript,ienumerable,enumeration
Hello im trying t develop a straight forward todo app using TypeScript and JQuery. I have an enum that lists task types: export enum TaskType { FrontEnd, BackEnd, Designer }; However looping through the emum using jquery.each or for loop, i get the following result, (values then indexes): FrontEnd, BackEnd,...

Extension method for IEnumerable which returns type of -this-

c#,ienumerable
Like I see, most IEnumerable extensions eats IEnumerable and then vomits also IEnumerable. Is it possible to make an extension method, which can eat any IEnumerable (like List) and then return the same type - List? For example, I want to iterate over collection, if something is wrong, I will...

Ienumerable of T, T is only available at runtime

reflection,ienumerable
I have a method with this signature public IEnumerable<T> GetAll<T>() where T : new() { // Orm Lite Version return Connection.LoadSelect<T>(); } At compile time I don't know the Type T. I only know the class name at runtime is it possible to call this method using reflection with something...

C# IEnumerable and string[]

c#,arrays,string,split,ienumerable
i searched for a method to split strings and i found one. Now my problem is that i can´t use the method like it is described. Stackoverflow answer It is going to tell that i cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string[]'. The provided method is: public static class EnumerableEx...

Converting string array to double array

c#,arrays,linq,collections,ienumerable
I have a file with alot of numbers, each index has 4 subnumbers no1 no2 no3 no4 no1 no2 no3 no4 no1 no2 no3 no4 The file is a cvs file, but I need to read the numbers into an array as type double and make an interpolating, so I...

How can I keep updating my ListBox synchronously

c#,wpf,ienumerable
I am calculating prime numbers bw two numbers using following code private static IEnumerable<int> GetPrimes(int from, int to) { for (int i = from; i <= to; i++) { bool isPrime = true; int limit = (int)Math.Sqrt(i); for (int j = 2; j <= limit; j++) if (i % j...

c# Implementing two enumerators for the same class

c#,list,ienumerable,ienumerator
Ok, so here's the basic code: class foo { String name; int property; } class bar { private List<foo> a; private List<foo> b; } I'd like to make it so that calling code can iterate over either list but I want to keep them protected from editing. I've looked into...