Menu
  • HOME
  • TAGS

Using reflection cast returned data to list

c#,reflection,ienumerable

You cannot create an instance of a List<T> if T is unknown at compile time. That's the generics' purpose, actually: strong typing. The foreach question is simple: object returnList = methodToCall.Invoke(null, null); IEnumerable enumerable = returnList as IEnumerable; if (enumerable != null) { foreach (var item in enumerable) { //...

Order by names starting by searched string alphabetically LINQ

c#,linq,sorting,ienumerable

Just add a ThenBy after that to order the stuff that starts with b and the stuff that doesn't. Also you might need to do a case insensitive comparison if you want a lower case "b" to match the names that start with an upper case "B". adminResult.OrderBy(m => m.Last_Name.ToLower()...

Implementing IEnumerable, Lists

c#,list,ienumerable

As one can see in the documentation about List<T>, this class has the signature: [SerializableAttribute] [DebuggerDisplayAttribute("Count = {Count}")] public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T> As you can see, it already implement IEnumerable<T> and IEnumerable. This means every List<T> instance can be used in a...

is IEnumerable enumerated on call of the method or when enumerating the response

c#,ienumerable

The list (enumerable) is only enumerated when the result of ProcessList (enum2) is enumerated: static void Main(string[] args) { var enumerable = Enum1(); Console.WriteLine("Enum1 retrieved"); var enum2 = Enum2(enumerable); Console.WriteLine("Enum2 called"); foreach (var e in enum2) { Console.WriteLine(e); } } private static IEnumerable<string> Enum1() { Console.WriteLine("Enum1"); yield return "foo"; }...

IEnumerable Group By user specified dynamic list of keys

c#,.net,asp.net-mvc,lambda,ienumerable

For my final solution to this problem, I used the coding approach from @jamespconnor 's answer but string as a grouping key could not help me much in my real scenario. So I used @tim-rogers 's basic idea of array as a grouping key and comparing the arrays using ArrayEqualityComparer....

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

c#,ienumerable

The problem with IEnumerable<T> is that Current is of type T. Instead of throwing an exception, default(T) is returned (it is set from MoveNextRare). When using IEnumerable you don't have the type, and you can't return a default value. The actual problem is you don't check the return value of...

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

c#,linq,ienumerable

Linq (i.e. the from i in r syntax you are using) requires you to implement the IEnumerable<T> interface, not IEnumerable. So, as Lee pointed out, you can just implement IEnumerable<int> like this: class Reeks : IEnumerable<int> { private int i = 1; public Reeks() { } public IEnumerator<int> GetEnumerator() {...

Transform collection of objects to a collection of tuples

c#,tuples,extension-methods,ienumerable

Something like this maybe? public static IEnumerable<Tuple<T, T>> ToTuples<T>(this IEnumerable<T> objects) { IEnumerator<T> enumerator = objects.GetEnumerator(); while (enumerator.MoveNext()) { T object1 = enumerator.Current; if (enumerator.MoveNext()) { yield return Tuple.Create(object1, enumerator.Current); } } } ...

Creating an extension method to wrap types as IEnumerables

c#,generics,extension-methods,ienumerable

Here is another attempt, inspired from Eric Lippert's excellent post at: http://stackoverflow.com/a/1451184/4955425. You can control the overloading resolution by placing your 2 extension methods at different levels in the namespace hierarchy. namespace MyExtensions { public static class HighPrecendenceExtensions { public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this IEnumerable<TSource> source) { return source; } }...

How to concat async enumerables?

c#,asynchronous,async-await,ienumerable

There is an existing project called Async Enumerable which answers this problem exactly. You could put it to use quite easily. For example: IAsyncEnumerable<string> GetAsyncAnswers() { return AsyncEnum.Enumerate<string>(async consumer => { foreach (var question in GetQuestions()) { string theAnswer = await answeringService.GetAnswer(question); await consumer.YieldAsync(theAnswer); } }); } This exposes an...

Accessing IEnumerable clears content

c#,cassandra,ienumerable

I don't know cassandra but i assume that the returned IEnumerable<T> is executed lazily(deferred). By consuming it (f.e. with foreach, ToList or Count) the query gets executed and the resources(f.e. the connection) are disposed/closed. If that's the case you could load it into an in memory collection, for example: var...

Missing directory and file info

c#,ienumerable,enumerate,directoryinfo,filesysteminfo

On 64-bit machines, some portions of the file system (and registry) are virtualized. It appears to me that you're running on a 64-bit machine and you are targeting x86 (or AnyCPU with the "Prefer 32-bit" setting) in your build. In 32-bit processes on 64-bit machines, C:\Windows\System32 is redirected to C:\Windows\SysWOW64....

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

asp.net-mvc,html-table,ienumerable,model-binding

One option could be as follows: namespace System.Web.Mvc { public static class ExecutorsExtensions { public static MvcHtmlString Executors(this HtmlHelper helper, List<TaskExecutor> executors) { var sb = new StringBuilder(); sb.Append("<table>"); for (var i = 0; i < executors.Count; i++) { sb.Append("<tr>"); sb.Append(string.Format("<td><input name=\"Executors[{0}].FirstName\" value=\"{1}\"></td>", i, executors[i].FirstName)); // add other cells here...

Get a all specific elements with flag

c#,arrays,linq,collections,ienumerable

So this is my understanding of what you're after (correct me if I'm wrong). You have a list of songs (in this case songList.Songs) and you want to get an IEnumerable<> collection of all songs with genreid == 18 (or any id). Just looking at your last line of code...

Extension method for IEnumerable which returns type of -this-

c#,ienumerable

I don't see how doing this could be beneficial, but you can solve the generics part of the problem like this: public static TEnumerable MyExtensionMethod<T, TEnumerable>(this TEnumerable enumerable) where TEnumerable : IEnumerable<T> { ... } However, you may find it difficult to actually implement such a thing because there is...

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

.net,vb.net,linq,ienumerable

You can use Range, Skip and Take to achieve your goal. Dim collection As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Dim parts As Integer = 4 Dim count As Integer = CInt(Math.Ceiling(collection.Count() / parts)) '= 3 Dim result As IEnumerable(Of IEnumerable(Of Integer)) =...

How to populate a collection with new objects, copying properties from another collection

c#,collections,ienumerable

Use List<Bar> instead of IEnumerable <Bar>, and assign the properties of Bar using its constructor as below IEnumerable <Foo> foos = queryResults; //I'll get my foo's with a LINQ query List<Bar> bars = new List<Bar>(); foreach (Foo f in foos) { bars.Add(new Bar() { Name = f.Name, Type = f.Type...

Converting IEnumerable to Dictionary

c#,dictionary,casting,ienumerable,deferred-execution

ToDictionary returns what you need. Just return that instead of returning query. return query.GroupBy(word => word) .ToDictionary(g => g.Key, g => g.Count()); ...

Union collections only if second TSource is not Null

c#,.net,linq,ienumerable

The problem you have here is not TSource being null; it's the object you want to get source from is null (group2). You can always use Enumerable.Empty to save your magic one liners. List<Type> allTypes = group.GetTypes().Union(group2 != null ? group2.GetTypes() : Enumerable.Empty<Type>()).ToList(); Or you can use a reusable Union...

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

c#,ienumerable

This is a matter of LINQ's lazy evaluation. Each time you iterate over list in GetBool1(), you're creating a new sequence of values. Changing the Value property in one of those objects doesn't change anything else. Compare that with GetBool2(), where you're got a call to ToList(), which means you're...

C# IEnumerable and string[]

c#,arrays,string,split,ienumerable

You have to use ToArray() method: string[] result = "bobjoecat".SplitBy(3).ToArray(); // [bob, joe, cat] You can implicitly convert Array to IEnumerable but cannot do it vice versa. ...

Add items to list from IEnumerable using LinQ

c#,linq,ienumerable

AddRange should do it for you: vm.Role.AddRange(query.Roles.Select(r => new CreateUserViewModel.Item { Label = r.Label, RoleNumber = r.RoleNumer })); AddRange takes an IEnumerable parameter and adds each item to the collection....

Ienumerable of T, T is only available at runtime

reflection,ienumerable

I'd give a Dynamitey library a go. You can do that in many different ways, but I prefer this one because of its simplicity. You can find it here. var name = InvokeMemberName.Create; var test = Dynamic.InvokeMember(Repository, name("GetAll", new[]{ParentTableClass })); foreach(var obj in test) { obj.SomeMethodFromMyType(); } Keep in mind,...

Combine path from a list of objects

c#,visual-studio,ienumerable

You can use LINQ: Path.Combine(items.Select(o => o.Name)) ...

Convert dictionary with List to IEnumerable

c#,dictionary,ienumerable

It's more efficient and easier to use the List<Foo> to add things but add it to a Dictionary<String, IEnumerable<Foo>>. That's no problem since List<Foo> implements IEnumerable<Foo>, it's not even necessary to cast. So something like this(pseudo code): var test = new Dictionary<String, IEnumerable<Foo>>(); foreach(var x in something) { var list...

“Left XOR” between two lists with LINQ

c#,linq,ienumerable

Using the Enumerable.Except: List<string> xorred = pIsinList.Except( diplayedBondsList.Select(x => x.isin)).ToList(); Note that this command will do implicitly a Distinct() on pIsinList (something that isn't explained in the MSDN, but that if you look at the source is quite clear), so if you had new[] { "A", "A" } in pIsinList,...

Calling Linq.Min on same IEnumerable returns different result

c#,linq,extension-methods,ienumerable,min

This could happen if enumerable changes between the calls. It seems GetNetworkRoutes uses lazy evalution to return the result. And that's why it's result is enumerated each time you call Min method on it. So the second returns different results and that's why the min. value you get is different....

IEnumerable Select statement with ternary operator

c#,linq,ienumerable,ternary-operator

Not sure if this was answered, But I think that this is related to the fact that you are using LINQ deferred execution. When writing LINQ queries, there is a difference between creating the query and executing it. Writing the select statement, is creating the query, adding ToList() executes it....

Enumerable.Where() not possible on IEnumerable?

c#,linq,ienumerable

Most LINQ to Objects methods work on the generic IEnumerable<T> type, rather than IEnumerable. Unfortunately, XmlNodeList only implements IEnumerable. It sounds like you're just looking for Cast, which is what the query expression with the explicit range variable type uses (and hence why the query expressions compile): XmlDocument doc =...

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

asp.net-mvc,asp.net-mvc-4,ienumerable

You view is displaying both a list of sample and what appears t be a form for a new sample. Start by creating a view model to represent what you want to display/edit public class SampleVM { public SampleVM { SampleCollection = new List<sample> } public List<sample> SampleCollection { get;...

Merge a sequence of elements into a defined number of blocks C#

c#,linq,ienumerable

Here is how the solution could looks like: public interface IMyInterface<T> { T MergeWith(params T[] others); T InnerElem { get; } } public class C : IMyInterface<int> { public C(int elem) { InnerElem = elem; } public int MergeWith(params int[] others) { return others.Sum() + InnerElem; } public int InnerElem...

GetEnumerator does not exist in this context

c#,linked-list,ienumerable,ienumerator

IEnumerable<string>.GetEnumerator() is an explicit interface implementation, so you need to call it on the instance, accessed as an interface. The easiest way to do this is to cast this: return ((IEnumerable<string>)this).GetEnumerator(); See How to call explicit interface implementation methods internally without explicit casting? for alternatives....

returning a list using a given type parameter in c#

c#,generics,ienumerable

You could do it by simply casting as the error message says return GetList().Select(m => m.Coordinator).Distinct() as IEnumerable<T>; This can be done with a generic repository by simply using an interface. If the class implementing this repository goes agianst a database or not doesnt really matter. public interface IRepository<TEntity> {...

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

c#,arrays,data-structures,ienumerable

I was under the impression that an IENumerable is essentially very similar to a linked list. I'm not really sure where you got that impression. An object implementing IEnumerable or IEnumerable<T> means "this object exposes an enumerator, which makes it iteratable", it has nothing to do directly to an...

IEnumerable to comma separated string

c#,string,ienumerable

You can use String.Join: string result = String.Join(", ", emails); ...

How can I keep updating my ListBox synchronously

c#,wpf,ienumerable

You are just posting too much. This code works as expected: public partial class MainWindow { public ObservableCollection<int> PrimeNumbers { get; set; } public MainWindow() { InitializeComponent(); PrimeNumbers = new ObservableCollection<int>(); } private void Button_Click(object sender, System.Windows.RoutedEventArgs e) { PrintPrimes(PrimeNumbers.Add, 1, 10000000, SynchronizationContext.Current); } private static void PrintPrimes(Action<int> action, int...

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

c#,list,ienumerable

Error message is quite clear. Your LINQ query returns collection of string, because you're selecting name.ProductName, but your method is declared to return collection of Products_Products. Change your LINQ query to return not just ProductName but the product itself: IEnumerable<Products_Products> x = new List<Products_Products>(); var test = (from name in...

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

c#,linq,ienumerable

Well, I guess this will work: "aqejqkndaasaamd".GroupBy(x => x).OrderByDescending(g => g.Count()).First().Key ...

c# Implementing two enumerators for the same class

c#,list,ienumerable,ienumerator

Don't expose a List<T>, expose something else, like an IReadOnlyList<T> instead: class bar { private readonly List<foo> a = new List<foo>(); private readonly List<foo> b = new List<foo>(); public IReadOnlyList<foo> A { get; private set; } public IReadOnlyList<foo> B { get; private set; } public bar() { A = a.AsReadOnly();...

Lazy initialization confusion

.net,vb.net,collections,ienumerable,lazy-initialization

Can't help you very much (not my main area of expertise).. Still, I've done some looking... I think that if you use a ResXResourceReader, and you set UseResXDataNodes = True like here When using the ResXResourceReader how can tell if the resource is an embedded file or if it is...

Easiest method to OrderBy a String using StringComparison.Ordinal

c#,string,compare,ienumerable,ordinal

There is a pre-built StringComparer that applies StringComparison.Ordinal - that's StringComparer.Ordinal: items.OrderBy(i => i.Name, StringComparer.Ordinal) ...

Remove a dictionary if all the keys has empty values in it?

c#,list,dictionary,ienumerable

Why do you add it to the list if you want to remove it later anyway? However, since the key is a string and the value is also a string this should work: finaldata = finaldata .Where(d => d.Values.Cast<string>().Any(str => !String.IsNullOrEmpty(str))) .ToList(); or finaldata.RemoveAll(d => d.Values.Cast<string>().All(String.IsNullOrEmpty)); If it's always a...

To ToList() or not to ToList()?

c#,performance,linq,ienumerable,tolist

Yes there is a difference and it can be significant. ToList() will iterate and append each iterated item into a new list. This has the effect of creating a temporary list which consumes memory. Sometimes you might want to take the memory penalty especially if you intend on iterating the...

ToSkip elements on C# circular list

c#,linq,extension-methods,ienumerable

You can implement this very easily with a yield return statement: public static IEnumerable<T> Jump<T>(this IList<T> data, int step) { int pos = 0; while(true) { yield return data[pos]; pos = (pos + step) % data.Count; } } ...

Converting Array to IEnumerable

c#,arrays,casting,type-conversion,ienumerable

The general Array base class is not typed, so it does not implement any type-specific interfaces; however, a vector can be cast directly - and GetValues actually returns a vector; so: public static IEnumerable<SomeType> AllEnums = (SomeType[])Enum.GetValues(typeof(SomeType)); or perhaps simpler: public static SomeType[] AllEnums = (SomeType[])Enum.GetValues(typeof(SomeType)); ...

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

To maintain the precision of the DateTime value so that it's as correct as possible while reducing database calls, you will want to make record of it as soon as the email has sent, but wait to persist the information until your email process has completed. I would say have...

LINQ Distinct not using the IEqualityComparer? [duplicate]

c#,.net,linq,ienumerable

Why is my Distinct() not working? Because Distinct first checks the hash code (since it's a quick check to see if two object could be equal) and then calls Equals. Since your GetHashCode implementations are all the same (and do not correspond to your Equals methods), Distinct is not...

Iterate over IEnumerable stops after first iteration

c#,ienumerable,ienumerator

Not sure why you need a List<T> there. if (idx < reeks.Count - 1) in MoveNext fails in second iteration. If it isn't necessary to implement your custom iterator, I'd do it with iterator blocks. private static IEnumerable<int> Reeks() { int num = 1; yield return num; while (true) {...

Why is it.current changing his values during debug?

c#,iterator,ienumerable,enumerator

Your problem is that you are using a single instance to iterate over in the Ranked.GetElem method. The first time you call ranked.GetElem, passing 0, the iterator will be moved one step (it.MoveNext). At this point the iterator is already pointing to the second element in your list. The next...

Why does this string extension method not throw an exception?

c#,null,comparison,ienumerable,argumentnullexception

You are using yield return. When doing so, the compiler will rewrite your method into a function that returns a generated class that implements a state machine. Broadly speaking, it rewrites locals to fields of that class and each part of your algorithm between the yield return instructions becomes a...

Getting Data From IEnumerable

c#,ienumerable

It seems that you can try using Linq, something like that: var codes = File .ReadLines(@"C:/AirCodes/RAPT.TXT") .Select(line => line.Split(',')) .Select(items => new { // I've created a simple anonymous class, // you'd probably want to create you own one Code = items[0].Trim('"'), //TODO: Check numbers Airport = items[2].Trim('"'), Country =...

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

c#,.net,linq,ienumerable,iqueryable

myEnumerable.AsQueryable() returns a custom object: new EnumerableQuery<TElement>(myEnumerable); (source code) This EnumerableQuery class implements IEnumerable<T> and IQueryable<T> When using the EnumerableQuery result of .AsQueryable() as an IEnumerable, the implementation of the interface method IEnumerable<T>.GetIterator() simply returns the original source iterator, so no change and minimal overhead. When using the result of...

c# loop through all fields of enum assigning values from string array

c#,for-loop,enums,ienumerable

Why not place the values onto the enum itself and then enumerate? For example using System.ComponentModel Description attribute we can add that information to the enum itself such as: public enum cardCreate { [Description("General Response")] MsgType = 0, [Description("V2.0")] WSName = 2, [Description("OmegaMan")] ReplyTo = 3, [Description("Windows 10")] SourceSystem =...

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

c#,reflection,ienumerable,var-dump,propertyinfo

This has nothing to do with the type implementing IEnumerable. Rather it's about the type having an indexer. Indexers are considered properties, but they're special properties that need to be given the parameter of the index when getting their value. If you don't, it errors as you're seeing here. You...

working of IEnumarable in for looping controls

c#,linq,ienumerable

The IEnumerable is an interface. When a type implements IEnumerable exposes an enumerator, that can be used for an iteration through the types elements. For instance an array implements this interface. Hence you can loop through it's items using a foreach statement: foreach(var item in array) { // ... }...

but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1

c#,asp.net-mvc,model,ienumerable,partial

As error states you are passing a wrong type. Change @{Html.RenderPartial("~/Views/Application/AppView.cshtml", new Example.Services.DAL.Application());} to: @{Html.RenderPartial("~/Views/Application/AppView.cshtml", new List<Example.Services.DAL.Application> { new Example.Services.DAL.Application() });} ...

Read skipped data

c#,.net,linq,ienumerable

Seems like your implementation does not call MoveNext() at the right time. You must call MoveNext() before you can get the Current element: public static IEnumerable<T> SkipTake<T>(this IEnumerable<T> input, int num, Action<List<T>> take) { var enumerator = input.GetEnumerator(); var chunk = new List<T>(); for (int i = 0; i <...

How efficient is IEnumerable.First and IEnumerable.Last?

.net,linq,queue,ienumerable,peek

If the collection implements IList<T>, then the indexer property is used in both First() and Last() (which is usually O(1), though it's not required to be). Otherwise, a call to First() will only take the first element (and exit immediately, if the enumerator supports deferred execution), but a call to...

Simple IEnumerable class definition [closed]

c#,.net,ienumerable

Like this (or I not understand your question?) class MyClass : IEnumerable<object> { public string FirstProperty { get; set; } public int SecondProperty { get; set; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<object> GetEnumerator() { yield return FirstProperty; yield return SecondProperty; } } ...

Concatenate multiple IEnumerable

c#,concatenation,ienumerable

Use SelectMany: public static IEnumerable<T> Concatenat<T>(params IEnumerable<T>[] lists) { return lists.SelectMany(x => x); } ...

Get an enumerator for the implemented interface from a class array

c#,ienumerable

The problem is that you want to return the interface while the array contains the class. You need to cast the items before returning an enumerator public IEnumerator<IReadonlyAssignedTasks> GetEnumerator() { return _assignedTasks.Cast<IReadonlyAssignedTasks>().GetEnumerator(); } ...

How to detect enum type passed to Enum[]

c#,enums,ienumerable

You could check it in the property, for example with Array.TrueForAll: private Enum[] _NotSupportedTypes; public Enum[] NotSupportedTypes { get { return _NotSupportedTypes; } set { if (!Array.TrueForAll(value, x => x.GetType() == typeof(MyEnum))) throw new ArgumentException("All enums must be MyEnum"); _NotSupportedTypes = value; } } As mentioned by Xanatos this won't...

Looping through an enum, TypeScript and JQuery

jquery,enums,typescript,ienumerable,enumeration

TypeScript enums when compiled into plain JS contain both the symbolic name AND the numeric values as properties and that explains why you get FrontEnd, BackEnd, Designer, 0, 1, 2 when you try to enumerate the properties of the object. As best I know, there is no post-compile way to...

Select the first object that match condition or an inner object

c#,lambda,ienumerable

This selects the first Foo with the specified SearchId both on top level or in any of the Foo instances in GroupedPackages. Package = response.lst .Concat(response.lst .Where(x => x.GroupedPackages != null) .SelectMany(x => x.GroupedPackages) ) .FirstOrDefault(x => x.SearchId == SearchId); ...

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

c#,generics,compiler-errors,ienumerable

Your ArrayFill(...) method is an extension method. Extension method must be created in a static and non-generic class. Create a new static class and move your method in it. public static class ExtensionMethod { public static void ArraysFill<T>(this T[] originalArray, T with) { for (int i = 0; i <...

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

c#,loops,search,ienumerable

While I know there are better ways to execute the search, I'm also very interested in WHY the code is going back into an exited loop, incrementing again, and causing the error The first thing is to understand what is actually going on: the code does not go back...

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

java,c#,iterator,ienumerable

Ok Buddy, it seams that what your search Method is trying to achieve is to run throughout an iterator until it finds a match. Then it will return an iterator starting from this match. Here is an alternative to your method that achieves what I just described: public RWIterator<T> Search(T...

Trouble combining Linq Expressions into a Func

linq,nhibernate,ienumerable,iqueryable

Consider this code: Func<T1, TResult> func = t => t == 5; Expression<Func<T1, TResult>> expression = t => t == 5; With this code, func will be a reference to compiled code, while expression will be a reference to an abstract syntax tree representing the lambda expression. Calling Compile() on...

iterate a number of dictionary items

c#,dictionary,ienumerable

The key is to build a set of arrays for each column of your data instead of for each rows like the Dictionary enumerator will provide you. This can be achieved through the use of the Aggregate extension method and a simple Select statement. // Assuming the following class as...

Iterating over IEnumerable using foreach skips some elements

c#,ienumerable

The call to ToList() will materialise the resulting selection of items as it looked at that point in time. Iterating over an IEnumerable will evaluate the expressions given for each item and yield them, one by one, and thus reality can have changed between iterations. In fact, it's probably very...

Enumerate all controls in a form (redundant)

vb.net,ienumerable,redundancy

There is IMHO too few information to answer your question "why that doesn't work for your specific case" Also the GetAllControls with two argument is missing in your code maybe the problem lies there Anyway I toyed a little with your code (but haven't tested it so it's more a...

Using IEnumerable> ds get the key, value pair [closed]

c#,dictionary,ienumerable

These following solutions maybe what your looking for, However you'll have to work out which one is more appropriate based on your circumstances Given var myKey = "someKey"; Assuming, your list of dictionaries contains the key your looking for, only once var aDictionary = MyEnumerable.Single(x => x.ContainsKey(myKey)); aDictionary[myKey] = myNewValue;...

Why do non-null XElements cause an NRE? [closed]

c#,linq-to-xml,extension-methods,ienumerable,xelement

Your element has a VendorId element, not a VendorID element (notice the casing), Element("VendorID") therefore returns null, and calling Value on that throws an NRE.

Linq expression to join a list and a dictionary

c#,linq,ienumerable,denormalization

var parts = new List<string> { "part1", "part2", "part3" }; var quantities = new Dictionary<string, int> { { "part1", 45 }, { "part3", 25 } }; var result = string.Join("|", from p in parts select quantities.ContainsKey(p) ? quantities[p].ToString() : ""); ...

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

c#,.net,linq,list,ienumerable

I'd approach by finding the latest date: var latestDate = items.Select(i => i.TakenDate).Max(); Then by filtering items with that date: var itemsWithLatestDate = items.Where(i => i.TakenDate == latestDate).ToList(); If you require all of them grouped in date order, then: var itemsByDate = items.GroupBy(i => i.TakenDate).OrderBy(g => g.Key); The latest date...

How to build a LINQ expression with Contains method from IEnumerable?

c#,linq,ienumerable,contains,expressionbuilder

It looks to me like you've just got the arguments the wrong way round. This: Expression.Call(method, property, value) means that you're calling: Enumerable.Contains(x.Col_id, ids) whereas you want Enumerable.Contains(ids, x.Col_id) So just try: var containsMethod = Expression.Call(method, value, property); EDIT: Next, you're building the wrong Contains type argument, I think. I...

Converting string array to double array

c#,arrays,linq,collections,ienumerable

If you want a double[][], so one array per line: double d; double[][] lineValues = file.Skip(5) .Select(l => l.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries)) .Where(arr => arr.Length == 4 && arr.All(s => double.TryParse(s, out d))) .Select(arr => arr.Select(double.Parse).ToArray()) .ToArray(); ...

Can IEnumerable be an alternative to Params[]? [duplicate]

c#,ienumerable,params

Using the params keyword importantly allows callers of your method not to wrap the arguments into a collection at all. With: public bool testMeth(params object[] input){ // ... things return purity >= REQUIRED_PURITY; //this is how to test meth, right? } The caller can call var is_good = testMeth("apples", new...

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

c#,linq,list,ienumerable

There's no need to create an empty list - just use IEnumerable<Product> retval; Your if/else will set the reference to the appropriate list from your DAL. Creating an empty list is probably not hurting anything (since the list won't take up much memory and will be eligible for GC pretty...

C# - Create Enumeraor that Get Values Randomly

c#,ienumerable,ienumerator

Using iterators with Random and infinite loop would be simplest solution. public IEnumerable<T> GetRandomElements<T>(T[] elements) { Random rand = new Random(); while(true) { int index = rand.Next(0, elements.Length); yield return elements[index]; } } ...

List passed as reference

c#,list,ienumerable,pass-by-reference

Reference types are passed by value. Meaning you pass the address of the reference in a new variable (address gets copied to a new memory location, that one is passed). In your submethod you are reassigning a new list to this new memory location, while the old memory location still...

C# pass generic type as a generic type parameter?

c#,generics,ienumerable

Why don´t you leave out the C-param at all? public static IEnumerable<T> RotateLeft<T>(IEnumerable<T> list, int count) { return list.Skip (count).Concat(list.Take(count)); } EDIT: As Suresh Kumar Veluswamy already mentioned you may also simply cast your result to an instance of C: public static C RotateLeft<C, T>(C list, int count) where C...

C# repeating IEnumerable multiple times

c#,ienumerable

You could use plain LINQ to do this: var repeated = Enumerable.Repeat(original, 3) .SelectMany(x => x); Or you could just write an extension method: public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source, int count) { for (int i = 0; i < count; i++) { foreach (var item in source) { yield...

Apply selectors on couples of elements of possibly infinite sequences C#

c#,extension-methods,ienumerable,yield-return

.NET already has an implementation of this exact functionality, Enumerable.Zip. As for how to implement it, if you wanted to do it yourself, it's fairly straightforward. Get an IEnumerator for each enumerable, while both have another value apply the result selector on the two current values and yield that result....

Do Enumerable.ElementAt in the same iteration of Enumerable

c#,ienumerable

Well any time you call ElementAt, if it's just a sequence (i.e. not an IList<T>) it will have to iterate all the way through the sequence as far as the given element number - there's no other way of it getting to the value. It sounds like you should just...

Getting words out of a text file with C#

c#,text-files,ienumerable,yield-return

this method yield returns all words, that start with a 'b' public static IEnumerable<string> ReadWords(this FileInfo fileInfo, Encoding enc) { using (var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.None)) { using (var reader = new StreamReader(stream)) { do { string[] line = reader.ReadLine().Split(' '); foreach (string word in line) {...

Relying on the iteration order of an unmodified HashSet

c#,mono,ienumerable,hashset

According to the reference source of HashSet (link), the iteration order is predictable in the absence of set modifications. public bool MoveNext() { if (version != set.m_version) { throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion)); } while (index < set.m_lastIndex) { if (set.m_slots[index].hashCode >= 0) { current = set.m_slots[index].value; index++; return true; } index++;...

FirstOrDefault on IEnumerable with non-nullable contents

c#,ienumerable

You can use the overload of DefaultIfEmpty to specify your fallback value. Then you also don't need FirstOrDefault but you an use First safely: return myEnumerable.DefaultIfEmpty(mySpecialValue).First(); ...

strange behaviour of linq usage

linq,ienumerable

Your query is linked to i field (using closures). But queries are execute after first cycle, so i already have its last value when query is executed. You can check "Access to modified closure" topic over internet (mainly it's about delegates but actually same thing works for expression trees)....

SortedSet - custom order when storing a class object

c#,asp.net,ienumerable,hashset,sortedset

Implement IComparer and pass it to the SortedSet constructor; See: https://msdn.microsoft.com/en-us/library/dd395024%28v=vs.110%29.aspx For example: I use this internal class SortedIndex { public double Comparable { get; set; } public int Index { get; set; } } internal class SortedIndexComparar : IComparer<SortedIndex> { public int Compare(SortedIndex x, SortedIndex y) { return x.Comparable.CompareTo(y.Comparable);...

Converting enumeration to IEnumerable issue

c#,.net,enums,ienumerable

It's hard to know for sure without a more complete code example. But I would expect this to work for you: EducationStatusEnum[] values = (EducationStatusEnum[])Enum .GetValues(typeof(EducationStatusEnum)); var list = from value in values select new SelectListItem() { Value = ((int)value).ToString(), Text = value.ToString() }; studentViewModel.LastEducationStatusList = list; In other words,...