【问题标题】:How to using List RemoveAll method with using interfaces? [closed]如何通过接口使用 List RemoveAll 方法? [关闭]
【发布时间】:2015-03-14 07:33:27
【问题描述】:

我可以创建列表并使用 RemoveAll 删除一些元素,但我需要使用接口来执行此操作。怎么做? 列表元素是字符串。

【问题讨论】:

  • 欢迎来到 StackOverflow。请仔细阅读:stackoverflow.com/help/how-to-ask
  • 请更具体。为什么你“需要使用接口来做到这一点”?如果RemoveAll() 适合您,您为什么不直接使用它呢?你试过什么代码?那段代码做了什么?这和你想要的有什么不同?请参阅stackoverflow.com/help/mcvestackoverflow.com/help/how-to-ask,获取有关如何以清晰、有用的方式提出问题的建议。
  • 这是我大学编程的功课。我需要使用接口从所有带有大字母的行列表中删除。
  • Why doesn't IList support AddRange,概念是一样的。 IList<> 不支持很多方法。
  • 我投票决定将此问题作为离题结束,因为它存在其他地方可以做作业。

标签: c# list interface


【解决方案1】:

这是你问的:

// An interface
public interface IMySelector
{
    bool IDontLike(string str);
}

// A class implementing the interface
public class MySelector : IMySelector
{
    public bool IDontLike(string str)
    {
        if (str.StartsWith("foo"))
        {
            return true;
        }

        return false;
    }
}

List<string> list = new List<string> { "foo1", "foo2", "bar1", "bar2" };

// Using the interface
IMySelector selector = new MySelector();

// Begin from last, it will be faster to remove
for (int i = list.Count - 1; i >= 0; i--)
{
    // Your condition
    if (selector.IDontLike(list[i]))
    {
        list.RemoveAt(i);
    }
}

有一个接口、一个实现该接口的类以及使用该接口选择要删除哪些元素的代码。请注意我如何从底部到顶部删除元素。它更快,并且需要更少的代码行:-)(如果你有一个 for [0... list.Count) 你会拥有if (selector...) { list.RemoveAt(1); i--; }

作为一个小提示,在 C# 中,您通常使用委托而不是单方法接口。

IEquatable&lt;T&gt;

public class MySelector : IEquatable<string>
{
    public bool Equals(string str)
    {
        // Strange concept of equality... All the 
        // words that start with foo are equal :-)
        if (str.StartsWith("foo"))
        {
            return true;
        }

        return false;
    }
}

List<string> list = new List<string> { "foo1", "foo2", "bar1", "bar2" };

// Using the interface
IEquatable<string> selector = new MySelector();

// Begin from last, it will be faster to remove
for (int i = list.Count - 1; i >= 0; i--)
{
    // Your condition
    if (selector.Equals(list[i]))
    {
        list.RemoveAt(i);
    }
}

【讨论】:

  • 在我的任务中你需要继承接口并重写相应的方法。
  • @user3750141 然后你应该向我们展示你的界面和你的代码。 “我可以创建列表并使用 RemoveAll 删除一些元素,但我需要使用接口来执行此操作”没有任何意义。
  • 我有 List ls = new List(); ls.add("dsfsd"); ls.add("DSFSDsd");我需要删除列表中所有具有大写字母的元素。例如 ls.Remove(new Compare()),其中 new Compare() - 它是一个类,继承了一些接口。
  • @user3750141 立即尝试
  • 可以使用IEquatable等标准接口吗?
【解决方案2】:

写一个扩展方法。叫它RemoveAll&lt;TItem&gt;。您想扩展接口IList&lt;TItem&gt;,因此相应地选择this-marked 参数。还要创建一个Func&lt;TItem, bool&gt; 参数。在方法体foreach中,使用委托实例,调用IList&lt;&gt;.Remove实例方法。

由于这是作业,我想我提供了足够的细节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 2015-05-28
    • 1970-01-01
    • 2010-12-10
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多