[英]Understanding Recursive LINQ function
我有下表
ItemNumber | FirstId | SecondId | ClientId
1 | 14 | 16 | NULL
2 | 17 | 18 | 1233242323
3 | 14 | 18 | 1233242323
5 | 15 | 12 | NULL
6 | 14 | 8 | 324234252
7 | 19 | 14 | 324234252
8 | 18 | 19 | 324234252
9 | 20 | 18 | 324234252
與以下 Class
public class ClientObject
{
public int ItemNumber { get; set; }
public int FirstId { get; set; }
public int SecondId { get; set; }
public double ClientId { get; set; }
public ClientObject()
{
}
}
給定 FirstId 和 ClientId,我想返回在 FirstId 列中找不到匹配項的 SecondId。 例如:從 FirstId 作為 20 ItemNumber 9) 開始,我想返回 8 (ItemNumber 6)。
我正在嘗試使用遞歸 function 方法,但不確定它是否正確,或者是否有更好的方法來解決這個問題。
public ClientObject GetItemRecursive(int initialId, double client)
{
var returnThis = databaseCtxt.TableToUse
.Where(x => x.FirstId == initialId && x.ClientId == client)
.AsEnumerable() // updated from suggestion
.Select(x => GetItemRecursive(x.SecondId, x.ClientId))
.FirstOrDefault();
return returnThis ;
}
我試圖在本地進行設置,但由於這是大型項目中非常小的一部分,所以我在這里創建了最小的示例。
您實際上需要檢查遞歸調用是否返回null
意味着沒有匹配並且您已經到了“葉子”。
public ClientObject GetItemRecursive(int initialId, double client)
{
var initial = databaseCtxt.TableToUse
.FirstOrDefault(x => x.FirstId == initialId && x.ClientId == client);
if(initial == null) return null;
var child = GetItemRecursive(initial.SecondId, client);
return child ?? initial;
}
或者你可以不遞歸地寫它
public ClientObject GetItemRecursive(int initialId, double client)
{
ClientObject parent = null;
bool childFound = true;
while(childFound)
{
var id = parent?.SecondId ?? initialId
var child = databaseCtxt.TableToUse
.FirstOrDefault(x => x.FirstId == id && x.ClientId == client);
if(child == null) childFound = false;
else parent = child;
}
return parent;
}
我會假設你正在尋找這樣的東西
public ClientObject GetItemRecursive(int initialId, double client)
{
return Inner(initialId, client, null);
ClientObject Inner(int id, double d, ClientObject acc )
{
var current = databaseCtxt.TableToUse
.Where(x => x.FirstId == id&& x.ClientId == d)
.FirstOrDefault();
if(current == null) return acc;
return Inner(current.SecondId, current.ClientId, current);
}
}
為方便起見,此代碼使用 C# 7.0 功能本地函數。
所以一般的方法是你有一個累加器( acc
),它在每次迭代時更新,直到你找不到繼續(對 db 的請求返回 null),當你到達這一點時,你通過所有嵌套調用返回累加器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.