locked
reading a passed anonymous type IEnumerable<T> to another class RRS feed

  • Question

  • User-2097295820 posted

        I have a class Product which has some attributes.

    public class Product{
    
          public int Name {get;set;}
      
          public string Category{get;set;}
    
          public long Total { get; set; }
    }
    private IEnumerable<T> Collectproducts(){
    var items = this.context.Products.Where(i=>i.ProductcategoryID == 1).Select(x=>new{ x.Name, x.Category}).AsEnumerable();

    return items
    }

    I am have read a collection of this Products, But I read only a few of the Name and Category of this Product in the Enumerable<T>

    So I want to pass this Enumerable<T> into another method in another class.

    But I dont know how to do this and items in the IEnumerable<T> in the second class

    Thursday, February 18, 2016 2:37 PM

All replies

  • User37182867 posted

    You can do it all with generics if you want or by keeping it boxed as a interface (IEnumerable<T>)

    If you need to access the name and category values in the other method then it may be easier to cast the IEnumberable in the second method to a class that would be defined with just the values that you need.

    Thursday, February 18, 2016 3:28 PM
  • User303363814 posted

    Keep it simple, just use the Product class you already have instead of introducing an anonymous type.  Change Collectproducts to be

    private IEnumerable<Product> Collectproducts() {
       return context.Products.Where(p => p.ProductcategoryID == 1)
                     .Select(p => new Product { Name = p.Name, Category = p.Category });
    }

    Now you have an IEnumerable<Product> to work with which should be easy. (If you are concerned then you could add Total = -1 to the constructor as a sentinel)

    I assume that the elements of context.Products are not of type Product, otherwise you could omit the Select clause as well.

    Thursday, February 18, 2016 10:53 PM
  • User-986267747 posted

    Hi skliz4rel,

    private IEnumerable<T> Collectproducts(){
    var items = this.context.Products.Where(i=>i.ProductcategoryID == 1).Select(x=>new{ x.Name, x.Category}).AsEnumerable();
    return items
    }

    reading a passed anonymous type IEnumerable<T> to another class

    According to your description, i couldn't understand you want to take an anonymous class as a generic, i suggest that you need to know what are Generics, and learn how to use generics in our project. In your Collectproducts method, we should return the list of generic that your defined, but you'd like to return the anonymous type, in my experience, it's not right.

    https://msdn.microsoft.com/en-us/library/sz6zd40f.aspx

    http://www.oracle.com/technetwork/articles/java/juneau-generics-2255374.html

    Best Regards,

    Klein zhang

    Friday, February 19, 2016 6:01 AM