मुझे यकीन नहीं है कि आप क्या देख रहे हैं, लेकिन यह कार्यक्रम:
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);
}
अपेक्षित उत्पादन पैदा करता है:
one: open
two: closed
four: open
five: closed
यह प्रोग्राम एनम के एक स्ट्रिंग प्रतिनिधित्व की तुलना करता है और समान आउटपुट उत्पन्न करता है:
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 ();
}
मैंने एक IEnumerable को दूसरे में बदलने के लिए यह एक्सटेंशन विधि बनाई, लेकिन मुझे यकीन नहीं है कि यह कितना कुशल है; यह सिर्फ पर्दे के पीछे एक सूची बना सकता है।
public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
{
foreach ( TSource source in sources )
yield return convert (source);
}
तब आप उस खंड को बदल सकते हैं:
where statusList.ConvertEach <string> (status => status.GetCharValue()).
Contains (v.Status)
और शुरुआत के List<string>
साथ बनाना छोड़ें ConvertAll ()
।
Contains()
विधि क्यों नहीं प्रदान करता है , और तब मुझे एहसास हुआ किAny()
इसके बजाय यह होना चाहिए । +1