C#枚举查询linq和一般类型?

时间:2017-06-09 07:12:39

标签: c# linq enums

所以我想知道,从我的枚举值列表中,存在多少特定的枚举值。

所以我写了像

public int GetNumFromList(List<Elements> list, Elements eType)
{        
    IEnumerable<Elements> query = //list.Where(p => p.GetType() == eType);
        from listchild in list
        where listchild == eType
        select listchild;
    /*
    Debug.Log("Cur check type is " + eType + " and now selected number is " + query.Count());
    if(query.Count() > 0)
        Debug.Log(" and query 0 value is "+ query.ToArray().GetValue(0) + " type is "+ query.ToArray().GetValue(0).GetType());
        */
    return query.Count();
}
  public enum Elements{Fire, Water, Wood, Metal, Earth, None}

所以这个效果很好,但我可以让它更短更整洁吗?

//list.Where(p => p.GetType() == eType);  This part doesn't worked.

如何为通用类型T?

制作这个

4 个答案:

答案 0 :(得分:3)

这适用于枚举和值类型

public int GetNumFromList<T>(List<T> list, T item)
{
    return list.Count(x => x.Equals(item));           
}

答案 1 :(得分:1)

试试这个:

IEnumerable<Elements> query = list.Where(p => p == eType);

答案 2 :(得分:1)

你可以这样做:

public int GetNumFromList(List<Elements> list, Elements eType)
{
  return list.Count(x => x == eType);
}

通用版本:

public int GetNumFromList<T>(List<T> list, T eType)
{
  return list.Count(x => x.Equals(eType));
}

请注意,您的类应覆盖通用案例中的Equals方法。

答案 3 :(得分:1)

  
    

如何为T普通型制作?不仅适用于[Elements]枚举。

  
public int GetNumFromList<T>(IEnumerable<T> list, T eType)
     where T : struct, IComparable, IFormattable, IConvertible

{
    return list.Count(x => x.Equals(eType));
}

问题在于,没有明确的方式说&#34; T必须是枚举&#34;。要求T为值类型,并实现IComparable,IFormattable和IConvertible,消除了许多(但不是全部)非枚举类型。