C# - Getting Type T From IEnumerable<T>
May 25, 2009is there a way to retrieve type T from IEnumerable<T> through reflection?
e.g.
i have a variable IEnumerable<Child> info; i want to retrieve Child's type through reflection
is there a way to retrieve type T from IEnumerable<T> through reflection?
e.g.
i have a variable IEnumerable<Child> info; i want to retrieve Child's type through reflection
And here is the code that produces the error
CODE:
How can i cast this one?
While learning to use LINQ in VB.NET, I came across the following:Dim x As IEnumerable = (some LINQ query)
If you can't instantiate an interface, but only a concrete implementation of it, why is this allowed? Is there some difference between doing Dim x as (Type) and Dim x as New (Type)?
The following line is giving me an InvalidCastException when trying to convert to IEnumerable type, even though I have implemented IEnumerable interface. Return New CountryInfo(CountryCodes(i), CountryNames(i)) (also in bold below)
Imports System
Imports Gaia.WebWidgets.HtmlFormatting
Imports System.Collections.Generic
Imports System.Globalization
[code]....
In many projects I work on, whenever I have to return a read only collection, I use the IEnumerable<T> interface and make it type specific like so:
CODE:
Most of the time, I return a List but in some functions and read only properties I return an array which also serves the purpose alright by kind courtesy of Extension Methods.
My question is am I violating any design principles by returning IEnumerable<T>s instead of specific types (e.g.: List<T>, HashSet<T>, Stack<T> or Arrays)?
I have an object called Result<T> that has a constructor which accepts an argument of IEnumerable<T>. I'd like to be able to pass in a datatable if possible.
I tried datatable.AsEnumerable(), but where I bind to the data it was complaining that 'MyProperty' is not a field or property on type 'DataRow' - which makes sense since 'MyProperty' isn't a property on 'DataRow', but it was a column in my datatable.Is there a way to convert a datatable to something that I can pass into the Result object and still have it bind to, say, a gridview?
I am creating a gridview and need to gather the data from various functions that return a type of IEnumerable. I've created gridviews using a dataset as a datasource, but how does one use multiple data sources(of IEnumerable) to populate one gridview? Like how do you combine all that into one dataset?
View 1 RepliesI tried using the linq Zip method on IEnumerable but it does not work for more than 2 arrays.Here is an example in Python of what I am trying to do(I got p - nested IEnumerable - and need q - another nested IEnumerable):
>>> l=['a','b','c']
>>> m=[1,2,3]
>>> n=['x','y','z'][code].......
1. When I try to do something like; Imports System.Collections
[Code]...
I see a couple of previously answered questions about adding an item to an IEnumerable in C#, but I'm stuck when trying to implement the proposed solution in VB.NET.
Option Strict On
Dim customers as IEnumerable(Of Customer)
' Return customers from a LINQ query (not shown)
customers = customers.Concat(New Customer with {.Name = "John Smith"})
The above code gives the error:
Option Strict On disallows implicit conversions from Customer to IEnumerable(Of Customer)
IEnumerable interface provides a instance method GetEnumerator that returns IEnumerator type opject .That's okey .But its very hezy to me that how IEnumerable objects are able to work with For Each loop ?When using For Each GetEnumerator method is not called directly from my code .Then from where and how GetEnumerator is called ?Basically my question is that when a class implements IEnumerabel interface then how a distinct behaviour is attached to that class?How it is used with For Each without calling GetEnumerator ?Here is the sample code that i am using :
Public Class Person
Public firstName As String
Public lastName As String
Public Sub New(ByVal firstName As String, ByVal lastName As String)
[code]....
i'm using Enumerable.Except to check if a DataTable in memory is in sync with the table in database.
The background is: this DataTable and other frequently used tables are stored in the Cache of a WebApplication. But meanwhile i'm convinced that this is not a good approach because it's a source for nasty errors that are difficult to reproduce/debug.
Therefore i've created a function that checks if database and memory are in sync, otherwise an error-log will be created. This works perfectly. If there is a row in memory that is not in database, this row will be shown below "Difference in database", the same applies in reverse. But if rows exist in both datasources(the PK idRMA) and some values differ, the log will contain this row in two versions(below "Difference in database" and "Difference in database"). It is not easy to see the differences on the first sight.
Q: Is it possible to select only the properties that caused Except to think that first sequence is not in second?
This is the the complete function(the first lines are relevant):
Public Shared Sub CheckRmaMemoryInSyncWithDB()
Dim inSyncText As String
Dim color As Drawing.Color
[Code]......
I'm trying to use the page control's collection with LINQ. Whereas this works:
dim l = Me.Controls.OfType(Of TextBox).AsQueryable()
the following return an ArgumentExceptionError:
dim l = Me.Controls.AsQueryable()
I used this but did not work :
Dim IENUM As IEnumerable = dat.getDanhSachDongSP
Dim bid as New BindingSource
bid.DataSource = IENUM
Dim dt2 As DataTable
dt2 = bid.DataSource
It show error "cant convert from IEnumberable to datatable"
when you use the object browser to see the features of a sortedlist elementat is not shown , but because a sorted list inherets features of ienumerable it works, cant that be corrected
View 1 RepliesI have an IEnumerable(Of System.Data.DataRowView) and would like to set it to be the datasource of a datagridview - however when I try I get no results my IEnumerable variable in the eg below is called xIEnum
DataGridView1.DataSource = xIEnum
However when I go
DataGridView1.DataSource = xIEnum.ToList
it works.... However I want the data to automatically update when I change the underlying datasource that the IEnum is mapped to?
I have the follow Linq query that is in a web application that was converted from .NET 1.1 to 3.5:
dim objListOfFilteredDataRows = from datarows as datarow in objDataSet.tables(0).rows _
where datarows("SomeColumn") = SomeValue
I have the exact same query in an application that was created using .NET 3.5 and the query returns an IEnumerable. However the query in the converted application is returning:
{Name = "WhereEnumerableIterator`1" FullName = "System.Linq.Enumerable+WhereEnumerableIterator`1[[System.Data.DataRow, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"}
**Edit: When I highlight the expression, the intellisense says that it doesn't know the type of objListOfFilteredDataRows and assumes its a type of "Object". Why is the type not infered in the converted 1.1 application but is infered in the "native" 3.5?**
What am I missing here? How do I convert the "WhereEnumeratorIterator`1 to an IEnumerable?
I've searched everywhere for some example code for this, but I can't figure out how to bind data returned from a function that looks like this to a gridview or dataset.
Public Function GetCompanyList() As IEnumerable(Of BusinessUser)
Return (From companyList In CorporateLists
Select companyList.User).Distinct()
[code].....
how to insert records with dapper-dot-net. However, the answers, while informative, didn't seem to point me in the right direction. Here is the situation: moving data from SqlServer to MySql. Reading the records into an IEnumerable<WTUser> is easy, but I am just not getting something on the insert. First, the 'moving records code':
// moving data
Dim session As New Session(DataProvider.MSSql, "server", _
"database")
Dim resources As List(Of WTUser) = session.QueryReader(Of WTUser)("select * from tbl_resource")
[code]....
Suppose I have an IEnumerable such as a List(TValue) and I want to keep track of whether this list is being accessed (to prevent issues with, say, adding to the list while it is being iterated over on a different thread); I can always write code such as the following:
Dim List1 As New List(Of Integer)
Dim IteratingList1 As Boolean = False
' ... some code ... '
[Code]....
(I realize this code is very arbitrary, but it illustrates what I'm talking about.)
My question is whether there's a better/cleaner way to perform this check than by manually updating and accessing a Boolean, as above. I feel like there must be, but, to my knowledge, there isn't any IEnumerable class with a built-in "I am being iterated over" method or property. And writing a new class that implements IEnumerable and contains such a property seems like overkill to me.
In VB.Net you can easily get the text value of the first child element of an XElement like so:Dim sChildValue = xeParent.<MyChild>.Value()Of course that syntax is not supported in C#, but it produces the same IEnumerable(Of XElement) result as the Elements() method. So we can rewrite the above like so:
Dim sChildValue = xeParent.Elements("MyChild").Value()This Value() extension method is handy because often you are working with small XML documents and you just want the first node that matches. (One thing that annoys me about this method is that it seems to return Nothing/null if the IEnumerable list is empty due to the specified element not being found. To work around this I have created my own ValueOrBlank() method that returns an empty string in that situation instead.)
My problem is that I can't do the same thing in C#:var sChildValue = xeParent.Elements("MyChild").Value(); // won't compile, can't find Value() method
I checked my references/imports and they match the VB.Net project where the same call works. Fortunately I am able to use my custom ValueOrBlank() extension method to accomplish the same thing. But I'm curious as to what's missing in my C# project. I tried right-clicking on the Value() method call in Visual Studio and clicking "Go To Definition" to see if the Object Browser could tell me where the extension method is kept, but it just shows the System.String class. Does that mean this is one of those sneaky VB.Net-only features that the compiler itself supports, like the XML Axis < MyChild > syntax?
If I have a List(Of x) and a List(Of y) is it possible to iterate over both at the same time?
Something like
for each _x as X, _y as Y in List(of x), List(of y)
if _x.item = _y.item then
'do something
end if
next
These lists may be of differing sizes. I am using .Net2.0 which I suspect is my downfall here as I have a feeling LINQ would solve something like easily by joining the lists on there common id.
This question is virtually the same as this SO post, only I'm looking for a VB.NET (.NET 4) solution. I've spun my wheels long enough trying to come up with a generic solution to solving this "power set" problem.
Dim choices As IEnumerable(Of String) = {"Coffee", "Tea", "Milk", "Cookies"}
Dim choiceSets = choices.CombineAll()
I'm looking for choiceSets to be an IEnumerable(Of IEnumerable(Of T)) so that I can do something like:
For each choiceSet in choiceSets
Console.WriteLine(String.Join(", ", choiceSet))
Next
[code]...
As you can see, this is every non-repeating combination from the source IEnumerable(Of T) (which could have 1 to many items in it - this example only had 4), it operates based on the order of the items in the source IEnumerable(Of T), and each item in the list is >= the previous item in terms of number of items in the inner IEnumerable(Of T).
For what it's worth, this is not homework; though it sure does feel like it. EDIT: Updated the example so it does not look like the result is alphabetically sorted, to stress that the source IEnumerable(Of T)'s existing order is used and added a 4th choice to clarify the sorting requirement within each set.
I've long since built a way around this, but it still keeps bugging me... it doesnt help that my grasp of dynamic LINQ queries is still shakey.
For the example:
Parent has fields (ParentKey, ParentField)
Child has fields (ChildKey, ParentKey, ChildField)
Pet has fields (PetKey, ChildKey, PetField)
[Code].....
The above Join call doesnt work. I sort of understand why it doesnt work, but hopefully it'll show you how I tried to accomplish this task.
After all this was done I would have appended a Select to finish the job.
I tried it with the PredicateBuilder with little success. I might not know how to use it right but it felt like it wasnt gonna handle the joining.
Is there an easy way to get the relative complement of two sets? Perhaps using LINQ?I have to find the relative compliment of a set A relative to B. Both A and B are of type HashSet<T> but I think the algorithm could be made more general (IEnumerable<T> or even ISet<T>)?
View 1 RepliesWhile trying to find an answer to my question, I came across a project called OTSe, which allows people to make they're own online 2d online games. The system is based on an open X, Y, Z square tile map. For the sake of easy understanding, lets say they're are 3 types of tiles. Tiles you CANNOT walk on, tiles you CAN walk on, and tiles that SLOW YOU'RE CHARACTER DOWN.The project team has created a API class for users to work with in order to develop tools. What I'm trying to do, using they're classes, is GET the all the tiles on the current floor I am walking on, and then display them in a tile grid on my form, changing they're color depending on what type of tile they are. If the tile is NOT WALKABLE, make the tile gray, if the tile IS WALKABLE, make the tile brown, and if the tile SLOWS YOU DOWN, make the tile red. I also need it to store the information of each tile, since tiles are objects, and have properties.
[code]...
How to give another function's returned value in LINQ Ienumerable.
Private function GetFruitColor(fruit) as string
'It returns fruit color.
'If valid fruit and color not available, it returns ""(empty string)
[code].....
'Below code is wrong. but please suggest me how to correct it. My intention is, I want output collection(say dictionary) of each fruitname and its color(returned by other function call) for all the fruits which the GetFruitColor is not nothing(it can be empty or valid string).
Dim query = _
fruits.Where(Function(fruit) k= GetFruitColor(fruit) if not k is nothing select fruit, k)
End Sub
In C#, when writing a function that returns an IEnumerble<>, you can use yield return to return a single item of the enumeration and yield break; to signify no remaining items. What is the VB.NET syntax for doing the same thing?
[Code]...
Ok, letīs see, iīm kind of new to this so letīs see if you can follow...I have a IEnumerable list of objects:
Dim
objStudentUsers
As
[code].....
I am stuck trying to convert code that works in C to VB. The C code is:internal IEnumerable<GraphicsBase> Selection
[Code]...
I have read the stuff about how this has to be done in VB using GetEnumerator method, but I just can't seem to get it to work.