So I want to know that, from my enum value list, how many specific enum value exists.
So I wrote like
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}
So this works well, but can I make this more shorter and neat?
//list.Where(p => p.GetType() == eType); This part doesn't worked.
And how can make this for generic type, T?
This should work for enums and value types
public int GetNumFromList<T>(List<T> list, T item)
{
return list.Count(x => x.Equals(item));
}
尝试这个:
IEnumerable<Elements> query = list.Where(p => p == eType);
You can do it as short as this:
public int GetNumFromList(List<Elements> list, Elements eType)
{
return list.Count(x => x == eType);
}
The generic version:
public int GetNumFromList<T>(List<T> list, T eType)
{
return list.Count(x => x.Equals(eType));
}
Notice your classes should override Equals
method in the generic case.
how can I make it for T general type? not only for [Elements] enum.
public int GetNumFromList<T>(IEnumerable<T> list, T eType)
where T : struct, IComparable, IFormattable, IConvertible
{
return list.Count(x => x.Equals(eType));
}
The problem is that there is no explicit way to say "T must be an enum". Requiring T to be a value type, and implement IComparable, IFormattable, and IConvertible, eliminates many (but not all) non-enum types.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.