我正在想辦法用 Linq 解決這個問題,有人知道如何做到這一點嗎?事實證明,試圖找到這個特定的用例非常具有挑戰性,所以我希望這個問題以前沒有被問過,即使我懷疑我只是找不到它。
public class Test
{
public int a;
public int b;
}
public Test[] testArray;
public enum Choice { A,B, Both = A|B }
public IEnumerable<int> GetEnumerable(Choice choice)
{
//need to use Linq methods to return an enumerable based on choice
}
//e.g testArray = { (1,2) (3,4) (5,6)
//calling GetEnumerable(Choice.A)
// 1,3,5
//calling GetEnumerable(Choice.Both)
// 1,2,3,4,5,6
每個人都集中在我的問題的錯誤方面,是的 [Flags] 屬性丟失了,是的,列舉項應該是 2 的冪才能用作標志。我已經標記了正確的答案,即回圈遍歷我之前所做的集合,我只是沒有意識到我可以回傳一個 IEnumerable 所以實作了一個列舉器
所有其他解決方案都使用 Linq,但過于依賴實體化新物件,這是一種很好的惰性快速方法,但這不是我想要的。
uj5u.com熱心網友回復:
不需要 Linq,我可能會使用一個switch運算式(盡管這里有一些 Linq):
public IEnumerable<int> GetEnumerable(Choice choice)
=> choice switch
{
Choice.A => testArray.Select(a => a.Item1),
Choice.B => testArray.Select(a => a.Item2),
Choice.Both => testArray.SelectMany(a => new[] { a.Item1, a.Item2 }),
_ => throw new ArgumentException("Invalid choice")
};
uj5u.com熱心網友回復:
您的列舉存在繼承問題,A|B == B,所以我將兩者都更改為自己的情況。這解決了一個 linq 查詢的問題:
public enum Choice { A, B, Both}
public class Test
{
public int A;
public int B;
public Test(int a, int b)
{
A = a;
B = b;
}
}
public class Program
{
public static void Main()
{
var tests = new List<Test>()
{
new Test(1, 2),
new Test(3, 4),
new Test(5, 6)
};
Console.WriteLine(string.Join(", ", GetEnumerable(tests, Choice.A)));
Console.WriteLine(string.Join(", ", GetEnumerable(tests, Choice.B)));
Console.WriteLine(string.Join(", ", GetEnumerable(tests, Choice.Both)));
/*
* Console Output:
* 1, 3, 5
* 2, 4, 6
* 1, 2, 3, 4, 5, 6
*/
}
private static IEnumerable<int> GetEnumerable(IEnumerable<Test> data, Choice choice)
=> data.SelectMany(d => choice switch
{
Choice.A => new List<int> { d.A },
Choice.B => new List<int> { d.B },
Choice.Both => new List<int> { d.A, d.B },
_ => throw new ArgumentException($"No case exists for Choice enum {choice}")
});
}
uj5u.com熱心網友回復:
如果您堅持使用單個 Linq 查詢,您可以嘗試SelectMany在哪里可以回傳所需的集合以進行展平,例如
public IEnumerable<int> GetEnumerable(Choice choice) => testArray
.SelectMany(item => choice == Choice.Both ? new int[] {item.A, item.B} :
choice == Choice.A ? new int[] {item.A} :
choice == Choice.B ? new int[] {item.B} :
new int[] {});
但是,我寧愿實作一個沒有任何 Linqforeach的簡單回圈:
// Since you use bit combinations, let's do it explicit with [Flags] attribute
[Flags]
public enum Choice {
None = 0, // let have "None" explicit
A = 1,
B = 2,
Both = A|B
}
public IEnumerable<int> GetEnumerable(Choice choice) {
foreach (var item in testArray) {
if (choice.HasFlag(Choice.A))
yield return item.A;
if (choice.HasFlag(Choice.B))
yield return item.B;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522811.html
標籤:C#林克
