Using LINQ to make Enterprise Search Results more usable

Posted Tuesday, March 25, 2008 9:58 AM by CoreyRoth

In my previous post about using the KeywordQuery class, I had one small omission.  The fact is that when you add your own managed properties using the SelectProperties collection of the keyword class, the data type you get back is a string[] containing 1 element instead of a string.  This can be quite annoying when you are attempting to do data binding as well as additional filtering.  I have found this to really only be the case when dealing with custom managed properties.  Default properties such as title and content source always return a string.  To combat this use LINQ to read the data into a new anonymous type.  You can then bind the data and filter as needed.

var results = from queryResult in queryDataTable.AsEnumerable()

              select new

              {

                  Title = queryResult.Field<string>("ContentSource"),

                  Size = (queryResult.Field<string[]>("Size").Any()) ? queryResult.Field<string[]>("Size")[0] : null                       

              };

In the above example, I specify ContentSource as a string just like normal.  However, for my custom manager property Size, I have to cast to a string[] and then I simply return the first element.  Technically, I should probably check to make sure that the element exists as well (but I am checking for null).  Once everything is copied into the anonymous type, you can bind, group, or filter it as needed.

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)