开发者

Generic Linq query on a DataGridView Datasource

开发者 https://www.devze.com 2023-01-23 18:08 出处:网络
I would like to implement a generic Linq query on a DataGridView.DataSource to retreive a row whith an idField. I did search MSDN, StackOverflow, etc... but didn\'t quite find what I\'m looking for. D

I would like to implement a generic Linq query on a DataGridView.DataSource to retreive a row whith an idField. I did search MSDN, StackOverflow, etc... but didn't quite find what I'm looking for. Does anyone have an idea on how I could implement it ?

This is the non-generic code, but I would like to make it work whatever the type of the DataSource is (as long as it implements IEnumerable I guess) and the name and type of the key field.

Dim query = (From note In notesList _
            Where note.IdNote = mIdNoteSelectionne _
            Select note).FirstOrDefault()

Dim ancienIndex As Integer = notesList.IndexOf(query)
开发者_运维技巧

noteList is a List(Of Note), Note is a simple entity class I created, with just members and properties

This is in VB, but feel free to send some C# code, I'll translate it.


Unfortunately you won't be able to do this for any datasource. Since you are trying to compare to an ID field, something that not every object has, you won't be able to. What you need to do, is define a base class or an interface that has an ID property on it. Then you can cast the datasource as an IEnumerable of your base class. using linqs Cast<> operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消