C# Beginner: Where has my IList.Where() method gon

2019-07-04 10:31发布

I've got another simple one (I think) that's stumping me. I have written a method in one of my controls that gets the latest version of a file in a CMS given it's filename (i.e. regardless of what folder the file resides in). I found it useful enough that I thought I'd chuck it in my CMSToolbox class, but when I do this I can no longer use the Where() method of a FileManager class provided by the CMS (which returns a list).

Here's a simplified example of my class:

using System;
using System.Collections.Generic;
using CMS.CMS;
using CMS.Core;
using CMS.Web;

namespace CoA.CMS {
    public class ToolBox
    {
        public CMS.CMS.File getLatestFileVersionByFilename(string filename, int GroupID)
        {
            IList<CMS.CMS.File> fileWithName = FileManager.GetGroupAll(false, GroupID).Where(file => currentFileVersionIsNamed(file, filename)).ToList<CMS.CMS.File>();
            return getLatestFileFromListOfFiles(fileWithName);

        }
        protected bool currentFileVersionIsNamed(CMS.CMS.File file, string name)
        {
        }
        protected CMS.CMS.File  getLatestFileFromListOfFiles(CMS.CMS.File file)
        {
        }
    }
}

When I do exactly the same thing in the context of a Control (really a class provided by the CMS which extends Control) I have access to the Where() method, but in my ToolBox class I don't. What gives? I figured that an IList would always allow access to the same methods from wherever you use it.

I'm a wrong again, haha :)


Edit: Filemanager.GetGroupAll() returns a CMSList which extends IList

3条回答
孤傲高冷的网名
2楼-- · 2019-07-04 11:13

IIRC, that .Where method is part of LINQ, and you need to add those using statements in your class to get the extension methods for the IEumerable interface.

查看更多
太酷不给撩
3楼-- · 2019-07-04 11:24

You need a using directive for System.Linq. .Where() is an extension method on IEnumerable<T> (which IList<T> implements) that is defined in the System.Linq namespace.

查看更多
Root(大扎)
4楼-- · 2019-07-04 11:27

Joel was first, but to expand on that: Where() is an extension method. Extension methods are static methods that act like real methods, and are declared like this:

static class NameNeverUsed
{
    public static void AnExtensionMethod(this string x)
    {
    }
}

And called like:

"hello".AnExtensionMethod();

They need to imported by using statements like anything else. So unlike Java/C++ a class can have methods declared outside it.

查看更多
登录 后发表回答