开发者

How to change a LINQ list into an arraylist

开发者 https://www.devze.com 2023-03-02 03:51 出处:网络
I have to write a query in a web application using LINQ but I need to change th开发者_Go百科at query into an array list. How can I change the query below to do this?

I have to write a query in a web application using LINQ but I need to change th开发者_Go百科at query into an array list. How can I change the query below to do this?

var resultsQuery =
    from result in o["SearchResponse"]["Web"]["Results"].Children()
    select new
    {
        Url = result.Value<string>("Url").ToString(),
        Title = result.Value<string>("Title").ToString(),
        Content = result.Value<string>("Description").ToString()
    };


If you really need to create an ArrayList, you can write new ArrayList(resultsQuery.ToArray()).

However, you should use a List<T> instead, by writing resultsQuery.ToList().

Note that, in both cases, the list will contain objects of anonymous type.


There is a .ToArray() method that'll convert IEnumerable to an Array.


ArrayList doesn't have a constructor or Add(Range) method that takes an IEnumerable. So that leaves two choices:

  • Use an intermediate collection that does implement ICollection: as both Array and List<T> implement ICollection can be used via the ToArray() or ToList() extension methods from LINQ.

  • Create an instance of ArrayList and then add each element of the result:

    var query = /* LINQ Expression */
    var res = new ArrayList();
    foreach (var item in query) {
      res.Add(item);
    }
    

The former method is simple to do but does mean creating the intermediate data structure (which of the two options has a higher overhead is an interesting question and partly depends on the query so there is no general answer). The latter is more code and does involve growing the ArrayList incrementally (so more memory for the GC, as would be the case for an intermediate Array or List<T>).

If you just need this in one place you can just do the code inline, if you need to do it in multiple places create your own extension method over IEnumerable<T>:

public static class MyExtensions {
  public static ArrayList ToArrayList<T>(this IEnumerable<T> input) {
    var col = input as ICollection;
    if (col != null) {
      return new ArrayList(col);
    }

    var res = new ArrayList();
    foreach (var item in input) {
      res.Add(item);
    }
    return res;
  }
}
0

精彩评论

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