【问题标题】:Getting the index of a list from a string in another list从另一个列表中的字符串获取列表的索引
【发布时间】:2013-07-05 21:42:49
【问题描述】:

我有两个列表:

public static List<Dinosaur> Dinosaurs = new List<Dinosaur>();
public static List<DinosaurSpecies> DinosaurSpeciesList = new List<DinosaurSpecies>();

我想使用第一个列表中的 Species 来查找第二个列表中 Species 的键。以下抛出“有一些无效参数”,但它确实说明了我正在尝试做的事情:

int index = MainWindow.DinosaurSpeciesList.FindIndex(MainWindow.Dinosaurs[i].Specie);

也就是说,恐龙列表[索引]中的物种出现在所有DinosaurSpecies的列表中的什么位置?

【问题讨论】:

  • 你为什么不使用类似地图或字典的数据结构?
  • 除非.SpeciePredicate&lt;T&gt;,否则可能无法编译。
  • 嗯,这些列表结构在整个程序中都使用过,并且到目前为止运行良好。我确信有一个简单的解决方案;可能只是我的语法。
  • 。指定 Dinosaur 类中的字段(谓词?以前从未听说过该词在此处以这种方式使用)。
  • 另外,“species”的单数是“species”。

标签: c# list indexing


【解决方案1】:

您可以通过将predicate 传递给FindIndex 方法来做到这一点:

int index = MainWindow.DinosaurSpeciesList.FindIndex(x => x.Specie == MainWindow.Dinosaurs[i].Specie);

基本上,你是说:找到Specie属性等于指定Dinosaur.Specie属性的元素的索引


一个简化且更易于理解的示例可能是:

Dinosaur dinosaur = GetDinosaurToFindSpeciesInformationFor();
int index = DinosaurSpeciesList.FindIndex(x => x.Specie == dinosaur.Specie);

当然,如果你打算只使用索引来获取 DinosaurSpecies 对象,你可以这样做:

DinosaurSpecies species = DinosaurSpeciesList.SingleOrDefault(x => x.Specie == dinosaur.Specie);
//NOTE: species will be null if there are no matches, or more than one match

【讨论】:

  • 感谢您的解释!另外,我“保证”永远不会有一个空匹配或多个匹配,因为当创建一个“个体”恐龙时,它会从 DinosaurSpeciesList 中获取它的“物种”。现在,我想用它作为索引来从 DinosaurSpeciesList 中提取其他数据(比如每天需要吃多少食物/KG)。
  • @zetar:刚刚查看了您的博客,我认为这是一个绝妙的想法,并祝您和您的团队在开发过程中好运。期待看到成品!
  • FindIndex 不是 LINQ 方法;此答案中使用的唯一 LINQ 方法是 SingleOrDefault
  • @Servy。正确的。您已通过测试。
  • @musefan system.LINQ 命名空间中定义的方法是 LINQ 方法,其余的不是。您可以使用 MSDN、Visual Studio 等来确定特定函数的定义位置,以及它是否是该命名空间中的函数之一。
【解决方案2】:

FindIndex 的参数错误。单参数形式需要一个 lambda(或者更具体地说,一个 Predicate&lt;T&gt;):

int index = MainWindow.DinosaurSpeciesList.FindIndex(x => x.Specie.Equals(MainWindow.Dinosaurs[i].Specie));

当然,这取决于您的 DinosaurSpecies 课程的外观。

ps。我喜欢恐龙

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2018-01-30
    • 2022-01-11
    • 2013-07-21
    • 2019-07-27
    相关资源
    最近更新 更多