הפעלת Linq Queries על פקדים המכילים Collections ללא חשיפה של IEnumerable מתאים
אחד מהיכולות החזקות של השפה שאנחנו משתמשים בהם רבות זהו היכולת להפעיל Linq to Objects על כל מי שמממש את:
IEnumerable<T>
ב - windows forms ישנם הרבה פקדים המכילים collections - כמו TabControl, TreeView ועוד.
הבעייה עם כל הפקדים הללו שהם חושפים את IEnumerable הרגיל, (ללא T) מה שגורם לכך שאי אפשר להפעיל עליהם שאילתות לינק.
כדי לתקן זאת ניתן להוסיף Extension Method מתאים לכל פקד ולהמיר את ה - IEnumerable לאחד שתומך ב - Generic, לדוגמא:
internal static class Extension
{
internal static IEnumerable<TabPage> AsEnumerator(this TabControl.TabPageCollection collection)
{
foreach (TabPage item in collection)
{
yield return item;
}
}
internal static IEnumerable<TreeNode> AsEnumerator(this TreeNodeCollection collection)
{
foreach (TreeNode item in collection)
{
yield return item;
}
}
}
בשביל הדוגמא - נניח שיש לי TreeView המכיל שמות של טבלאות וכל טבלה מכילה את שמות העמודות (כמו ב - Sql Server Managment Studio)
כעת אני מעוניין לייצר סקריפט עבור שאילתת select - נוכל לכתוב את הקוד הבא:
string.Format("SELECT {0} FROM {1}",
treeView1.SelectedNode.Nodes.AsEnumerator()
.Select(x => "[" + x.Text + "]")
.Aggregate((x, y) => x + ", " + y),
treeView1.SelectedNode.Text);
התוצאה של הקוד הקודם תהיה:
SELECT [Account_Id], [Loyalty_Id] FROM AccountLoyalties
ברגע שנוסיף את ה - Extension Method הללו עבור הפקדים השונים, נשדרג אותם ונוכל להפעיל עליהם שאילתות Linq