Nie jestem pewien, czego dokładnie szukasz, ale ten program:
public class Building
{
public enum StatusType
{
open,
closed,
weird,
};
public string Name { get; set; }
public StatusType Status { get; set; }
}
public static List <Building> buildingList = new List<Building> ()
{
new Building () { Name = "one", Status = Building.StatusType.open },
new Building () { Name = "two", Status = Building.StatusType.closed },
new Building () { Name = "three", Status = Building.StatusType.weird },
new Building () { Name = "four", Status = Building.StatusType.open },
new Building () { Name = "five", Status = Building.StatusType.closed },
new Building () { Name = "six", Status = Building.StatusType.weird },
};
static void Main (string [] args)
{
var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
var q = from building in buildingList
where statusList.Contains (building.Status)
select building;
foreach ( var b in q )
Console.WriteLine ("{0}: {1}", b.Name, b.Status);
}
daje oczekiwany wynik:
one: open
two: closed
four: open
five: closed
Ten program porównuje ciąg reprezentujący wyliczenie i generuje te same dane wyjściowe:
public class Building
{
public enum StatusType
{
open,
closed,
weird,
};
public string Name { get; set; }
public string Status { get; set; }
}
public static List <Building> buildingList = new List<Building> ()
{
new Building () { Name = "one", Status = "open" },
new Building () { Name = "two", Status = "closed" },
new Building () { Name = "three", Status = "weird" },
new Building () { Name = "four", Status = "open" },
new Building () { Name = "five", Status = "closed" },
new Building () { Name = "six", Status = "weird" },
};
static void Main (string [] args)
{
var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
var statusStringList = statusList.ConvertAll <string> (st => st.ToString ());
var q = from building in buildingList
where statusStringList.Contains (building.Status)
select building;
foreach ( var b in q )
Console.WriteLine ("{0}: {1}", b.Name, b.Status);
Console.ReadKey ();
}
Utworzyłem tę metodę rozszerzenia, aby przekonwertować jeden IEnumerable na inny, ale nie jestem pewien, jak wydajna jest; może po prostu utworzyć listę zakulisową.
public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
{
foreach ( TSource source in sources )
yield return convert (source);
}
Następnie możesz zmienić klauzulę where na:
where statusList.ConvertEach <string> (status => status.GetCharValue()).
Contains (v.Status)
i pomiń tworzenie List<string>
z ConvertAll ()
na początku.
Contains()
metody, a potem zdaję sobie sprawę, że tak powinno byćAny()
. +1