0

I had a ObservableCollection (fields like username,firstname,lastname,password,address,contact no etc) which contains a huge set of rows, and also I am having a datatable (columns like SNo, username,status) which is having a limited number of rows only.

Now what I need to filter the ObservableCollection based on the usernames present in the datatable in the datatable and bind the ObservableCollection to datagrid using linq. I done a sample linq Query it does not produce exact data.

 var res = from a in Settings.GetInstance().ObservableClass 
           where dtStatusTable.Rows.Contains(a.UserName)
           select a;
 Settings.GetInstance().ObservableClass = res as ObservableCollection<IObservableClass >;

Note: UserName is unique and may be contains similar but not exact. Like usernames may be like Manikandan, Mani, ManikandanSekar etc. Kindly give me a solution to filter the data.

  • http://stackoverflow.com/questions/11961059/check-if-string-exists-in-datatable – eran otzap Oct 28 '13 at 15:43
  • Thanks for your quick reply eran otzap, but it is searching a table with a particular string, whereas what i need is to filter a huge set based on a small set dynamically using linq – Manikandan Sekar Oct 28 '13 at 15:48

2 Answers2

1

Your current query says "where the datatable has a row of a.UserName", when it sounds like you want the query to say "where the datatable has a row that contains a.UserName in a specific column". You can make this a little clearer by doing something like this (not sure what your exact types are, so this is just some psuedo-query):

var usernamesInDataTable = dtStatusTable.Rows.Select(r => r.UserName);

var query = from a in ObservableClass
            where userNamesInDataTable.Contains(a.UserName)
            select a;
Ocelot20
  • 10,510
  • 11
  • 55
  • 96
0

Perhaps you can do something like this which should select items with an exact match of username:

YourObservableCollection = new ObservableCollection<YourDataType>(
    from item in YourObservableCollection 
    join row in YourDataTable on item.username equals row.username
    select item);

It's kind of tricky writing LinQ queries without data and intellisense, so please forgive me if there are errors in it.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • Thanks for your time Sheridan. `Settings.GetInstance().ObservableClass= new ObservableCollection( from item in Settings.GetInstance().ObservableClass join row in dtRecentInteractions on item.UserName equals row.UserName select item);` I tried this but it shows error in join – Manikandan Sekar Oct 29 '13 at 09:14
  • The error is that we cant implement the join in the above query – Manikandan Sekar Oct 30 '13 at 13:06
  • What does the error *actually* say? Surely there is more information than that? – Sheridan Oct 30 '13 at 13:08