I'm trying to work with the .NET AJAX autocompletion extension. The extension is expecting the following...
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
My database queries are in a LINQ var object. I'm getting compile-time errors about not being able to convert type IQueryable to string[].
InventoryDataContext assets = new InventoryDataContext();
var assetsInStorage = from a in assets.Assets
where a.Name.Contains(prefixText)
orderby a.Name ascending
select new[] { a.Manufacturer.Name, a.Name };
return (string[])assetsInStorage;
In order to get an string[]
at first you must select only one string property on your query, not an anonymous object:
var assetsInStorage = from a in assets.Assets
where a.Name.Contains(prefixText)
orderby a.Name ascending
select a.Manufacturer.Name; // or a.Name
assetsInStorage
at this moment is an IEnumerable<string>
, and then you should convert it to string[]
by:
return assetsInStorage.ToArray();
Your assetsInStorage
doesn't appear to be an IEnumerable<string>
... as such, you'd have to project your anonymous type into a string.
assetsInStorage.Select(a=>a[0] + a[1])
(Or however you want to convert that anonymouns type to a string.)
And then you can return .ToArray()
:
return assetsInStorage.Select(a=>a[0]+a[1]).ToArray();
This should do the trick:
InventoryDataContext assets = new InventoryDataContext();
var assetsInStorage = from a in assets.Assets
where a.Name.Contains(prefixText)
orderby a.Name ascending
select String.Concat(x.ManufacturerName, " ", x.Name);
return assetsInStorage.ToArray();
EDITED based on comment... EF is able to interpret String.Concat(), so the additional enumeration wasn't necessary.
If you want a single array that contains both a.Manufacturer.Name
and a.Name
for each of the assets, you can do that with a slight modification of CMS's answer:
var assetsInStorage = from a in assets.Assets
where a.Name.Contains(prefixText)
orderby a.Name ascending
select new[] { a.Manufacturer.Name, a.Name };
At this point, assetsInStorage
is an IEnumerable<string[]>
which also counts as an IEnumerable<IEnumerable<string>>
. We can flatten this down to a single IEnumerable<string>
using SelectMany
and then turn it into an array.
return assetsInStorage.SelectMany(a => a).ToArray();
In this way, you're not required to select only a single string value.
尝试:
return assetsInStorage.ToArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.