Making a custom class IQueryable

后端 未结 2 1645
广开言路
广开言路 2021-02-13 22:14

I have been working with the TFS API for VS2010 and had to query FieldCollection which I found isn\'t supported by LINQ so I wanted to create a custom class to make the Field an

相关标签:
2条回答
  • 2021-02-13 23:10

    In your case of wrapping and building a class around an existing IEnumerable Collection type i.e. List<Field>,

    you might just use a set of "forward function" wrappers that expose the IQueryable<Field> interface:

    public class WorkItemFieldCollection : IEnumerable<Field>, IQueryable<Field>
    {
        ...
        #region Implementation of IQueryable<Field>
    
        public Type ElementType
        {
            get
            {
                return this._fieldList.AsQueryable().ElementType;
            }
        }
    
        public Expression Expression
        {
            get
            {
                return this._fieldList.AsQueryable().Expression;
            }
        }
    
        public IQueryProvider Provider
        {
            get
            {
                return this._fieldList.AsQueryable().Provider;
            }
        }
    
        #endregion
        ...
    }
    

    You can now directly query your WorkItemFieldCollection:

    var workItemFieldCollection = new WorkItemFieldCollection(...);
    var Fuzz = "someStringId";
    var workFieldItem = workItemFieldCollection.FirstOrDefault( c => c.Buzz == Fuzz );
    
    0 讨论(0)
  • 2021-02-13 23:18

    If you want an object to be usable by LINQ, implement IEnumerable<T>. IQueryable<T> is overkill for LINQ to Objects. It is designed for converting the expressions into another form.

    Or if you want, you can do this

    FieldCollection someFieldCollection = ...
    IEnumerable<Field> fields = someFieldCollections.Cast<Field>();
    
    0 讨论(0)
提交回复
热议问题