【问题标题】:Return Indices of first elements in a nested list返回嵌套列表中第一个元素的索引
【发布时间】:2015-01-20 21:19:44
【问题描述】:

我有一个自定义类型的列表,其中包含一个枚举类型作为属性。
我想在我的列表中找到枚举类型中每个枚举的所有第一次出现的索引。

我考虑过输出不同的类型,然后在这个序列中找到第一个,但第一个函数需要一个我收到错误的类型

using System;
using System.Collections.Generic;

namespace space
{

    TypeEnum { E1, E2, E3}

    public class Class1
    {
        public TypeEnum Eobj { get; set; }
        public double doubObj { get; set; }

        public Class1()
        {
            doubObj = 0.0;
            Eobj = TypeEnum.E1;

        }

        public Class1(double doubObjIn, TypeEnum EobjIn)
        {
            doubObj =  doubObjIn;
            Eobj = EobjIn;

        }
    }

    public static void Main()
    {
        List<Class1> list1 = new List<Class1>();
        Class1 o1 = new Class1(1, TypeEnum.E1);
        Class1 o2 = new Class1(2, TypeEnum.E1);
        Class1 o3 = new Class1(3, TypeEnum.E2);

        list1.Add(o1);
        list1.Add(o2);
        list1.Add(o3);


        // first try to get a sequence of which enumerated types are present
        var ba = list1.Select(o => o.Eobj).Distinct();
        //then try to find where they are in the list
        var bb = list1.Select(o => o.Eobj).First(ba);



    }

}

【问题讨论】:

  • 这段代码有错误吗?或者您的预期结果是什么?
  • 我收到一个错误,因为第一个函数是通用的,需要我输入类型源
  • 第二个没有意义。 First(当传递另一个列表作为参数时)应该做什么?你能更好地解释期望的行为吗?
  • 您的“嵌套列表”在哪里?您的代码示例中只有一个列表。请注意,您得到的编译器错误是编译器可以提供的最好的错误,但问题不在于您需要提供类型参数,而是 First() 方法将委托实例作为参数,而不是列表。你的意思是像ba.First(); 而不是list1.Select(o =&gt; o.Eobj).First(ba);?您需要更清楚地了解您期望从这段代码中得到什么输出。
  • 我已经更新了文本以试图澄清

标签: c# collections generic-list


【解决方案1】:

这就是我理解的您的要求。 给定一个包含这些项目的列表

List<Class1> list1 = new List<Class1>();
Class1 o1 = new Class1(1, TypeEnum.E1);
Class1 o2 = new Class1(2, TypeEnum.E1);
Class1 o3 = new Class1(3, TypeEnum.E2);

您希望将其简化为仅找到一个包含TypeEnum 的对象的列表。如果是这种情况,请考虑使用DistinctBy

然后,您可以简单地调用它使用

var newList = list1.DistinctBy(a => a.Eobj);

如果你只想获取索引(索引?),那么你可以这样写:

var indexes = list1.Select(x => x.Eobj).Distinct().Select(type => 
    list1.FindIndex(o => o.Eobj == type)).ToList();

如果你想找出枚举值,以及它们在列表中对应的索引,你可以这样写:

var typesWithIndexes = list1.Select(x => x.Eobj).Distinct()
  .Select(type => new
    {
      Type = type,
      Index = list1.FindIndex(o => o.Eobj == type)
    }).ToList();

【讨论】:

  • 我不是要减少列表,而是要找出存在哪些 TypeEnum 以及第一次出现的索引是什么
  • 好的,谢谢,我想最后一个是我所追求的……我现在就测试一下
猜你喜欢
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2014-11-06
  • 2015-12-16
  • 2017-03-03
  • 2011-01-25
  • 2018-05-30
  • 2013-12-24
相关资源
最近更新 更多