網路核心應用。我的應用程式中有以下查詢
var result = sourceProposal.Quotes
.Where(x=>x.QuotationId == sourceQuoteId)
.FirstOrDefault()
.QuoteLines.Select(x=>(x.Quantity,x.WtgType)).ToArray();
這會產生兩個陣列元素,例如
0 element 1, "string1"
1 element 2, "string2"
我期待的是
(int[] sourceQuantity, string[] destinationTurbineType) = sourceProposal.Quotes
.Where(x=>x.QuotationId == sourceQuoteId)
.FirstOrDefault()
.QuoteLines.Select(x=>(x.Quantity,x.WtgType)).ToArray();
我想復制到元組 int[] sourceQuantity,string[] destinationTurbineType這段代碼不起作用,并且拋出錯誤不包含解構式的定義,并且沒有可訪問的擴展方法 Decontruct 接受型別的第一個引數int(sourceQuantity, string destinationTurbineType)[]。
有人可以幫我將值復制到sourceQuantityand destinationTurbineType。任何幫助,將不勝感激。謝謝
uj5u.com熱心網友回復:
Select<TSource,TResult>回傳選擇器(IEnumerabe<TResult>/ IQueryable <TResult>)回傳的型別的可列舉/可查詢。
如果您想使用 LINQ 實作此目的,您可以使用Aggregate:
// note that sourceQuantity and destinationTurbineType would be lists, not arrays
var (sourceQuantity, destinationTurbineType) = sourceProposal.Quotes
.Where(x=>x.QuotationId == sourceQuoteId)
.FirstOrDefault()
.QuoteLines
.Aggregate((ints: new List<int>(), strs: new List<string>()), (aggr, curr) =>
{
aggr.ints.Add(curr.Quantity);
aggr.strs.Add(curr.WtgType);
return aggr;
});
或者只是使用簡單的for回圈并將資料復制到目標陣列(可能移動到一些擴展方法)。沿著這條線的東西:
var quoteLines = sourceProposal.Quotes
.Where(x=>x.QuotationId == sourceQuoteId)
.FirstOrDefault()
.QuoteLines; // assuming it is materialized collection with indexer like an array or list
int[] sourceQuantity = new int[quoteLines.Length]; // or Count
string[] destinationTurbineType = new string[quoteLines.Count()];
for(int i = 0; i < quoteLines.Length; i )
{
var curr = quoteLines[i];
sourceQuantity[i] = curr.Quantity;
destinationTurbineType[i] = curr.WtgType;
}
uj5u.com熱心網友回復:
目前沒有內置的 LINQ 方法可以做到這一點。但是您可以撰寫自己的擴展方法。類似于以下內容:
public static class EnumerableExtensions
{
public static (TFirst[] xs, TSecond[] ys) Unzip<TFirst, TSecond>(this IEnumerable<(TFirst, TSecond)> zipped)
{
var xs = new List<TFirst>();
var ys = new List<TSecond>();
foreach (var (x, y) in zipped)
{
xs.Add(x);
ys.Add(y);
}
return (xs.ToArray(), ys.ToArray());
}
}
var (xs, ys) =
new[] { 1, 2, 3 }
.Zip(new[] { "a", "b", "c" })
.Unzip();
Console.WriteLine(string.Join(", ", xs)); // 1, 2, 3
Console.WriteLine(string.Join(", ", ys)); // a, b, c
或者在您的示例中,您可以使用:
(int[] sourceQuantity, string[] destinationTurbineType) = sourceProposal.Quotes
.Where(x=>x.QuotationId == sourceQuoteId)
.FirstOrDefault()
.QuoteLines.Select(x=>(x.Quantity,x.WtgType)).Unzip();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470995.html
