我有一個方法可以引入一個字串串列和一個 id,我必須回傳一個包含字串串列和 id 的元組,該元組需要過濾并且只回傳一個字串和一個 id,它們不能我所堅持的同樣是如何在回傳時擺脫演員表,我想確保我回傳的每個字串都有正確的關聯 id。
public static List<(string,int)> ModifiedData(List<string?> changedData, int? id)
{
//declare a tuple to keep track of all changes and id
var result = new List<(string change, int? cId)>();
if (changedData != null)
{
foreach (var change in changedData)
{
//add the change and id to a list of tuples
result.Add((change, id));
}
}
//delete all of the same instances in the array and return and array
var filteredChanges = result.Select(x => (x.change, x.cId)).Distinct();
//return the tuple** how can i also get rid of this cast
return (List<(string, int)>)filteredChanges;
}
uj5u.com熱心網友回復:
目前你的演員會在運行時拋出一個例外,因為它不是一個串列。
您可以顯著簡化您的代碼:
public static List<(string, int)> ModifiedData(List<string?> changedData, int? id)
{
return changedData?
.Select(s => (s, id.GetValueOrDefault()))
.Distinct()
.ToList() ?? new List<(string, int)>(0);
}
但是,也許您想為字串和/或 id 添加空檢查。您可以添加一個Where
:
return changedData?
.Where(s => s != null)
.Select(s => (s, id.GetValueOrDefault()))
.Distinct()
.ToList() ?? new List<(string, int)>(0);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527775.html
標籤:C#。网列表元组