返回嵌套列表中第一个元素的索引

时间:2015-01-20 21:19:44

标签: c# collections generic-list

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

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

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);



    }

}

1 个答案:

答案 0 :(得分:0)

这就是我所理解的你的要求。 给出包含这些项目的列表

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();
相关问题