开发者

Convert anonymous type to array or arraylist. Can it be done

开发者 https://www.devze.com 2022-12-19 00:24 出处:网络
Trying to retrieve data using linq from a database. I would like to use anonymous types and convert to an Ilist, Array, ArrayList or Collection.The data is used in a third party object that accepts Il

Trying to retrieve data using linq from a database. I would like to use anonymous types and convert to an Ilist, Array, ArrayList or Collection. The data is used in a third party object that accepts Ilist, arraylist or collections.

I can't seem to get this to work. I get the following error, "Sequence operators not supported for type 'System.String'"

using (var db = new dbDataContext())
{
    var query = from e in db.people
              开发者_JAVA技巧  select new
                {
                    Count = e.LastName.Count()
                };

    Array test;
    test = query.ToArray();
}


It's got nothing to do with converting the results to array lists, or even anonymous types. Here's another version of your code which will fail:

using (var db = new dbDataContext())
{
    var query = db.people.Select(x => x.LastName.Count());
    foreach (int x in query)
    {
        Console.WriteLine(x);
    }
}

That will still fail in the same way - because it's the translation of this bit:

x => x.LastName.Count()

into SQL which is causing problems.

Change it to:

x => x.LastName.Length

and I suspect you'll find it works. Note that this isn't really a C# issue - it's just LINQ to SQL's translation abilities.

I would suggest that you don't use an anonymous type here though - it's pointless. Maybe this isn't your complete code, but in general if you find yourself creating an anonymous type with a single member, ask yourself if it's really doing you any good.


The ArrayList class has a constructor that accepts ICollection.
You should be able to feed it a List version of your LINQ result.

using (var db = new dbDataContext()) {
        var query = from e in db.people
                    select new { Count = e.LastName.Count() };

        ArrayList list = new ArrayList(query.ToList());
}

I don't have Visual Studio here (I'm on my Mac), but it might be of help. (ToArray should suffice as well)

You might need to replace your Count() by Length.

0

精彩评论

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