2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
使用擴(kuò)展功能Flatten:
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> e, Func<T, IEnumerable<T>> flattenFn) => e.SelectMany(c => c.Flatten(flattenFn));
public static IEnumerable<T> Flatten<T>(this T current, Func<T, IEnumerable<T>> childrenFn) {
var working = new Stack<T>();
working.Push(current);
while (working.Count > 0) {
current = working.Pop();
yield return current;
if (childrenFn(current) != null)
foreach (var child in childrenFn(current))
working.Push(child);
}
}
您可以展平您的原件ITEMS List,然后檢查您的新項(xiàng)目是否在其中:
var exists = ITEMS.Flatten(x => x.Child).Select(x => x.itemName).Contains(newItemID);
如果您經(jīng)常這樣做,那么考慮基于散列的結(jié)構(gòu)(例如 a)可能是明智的,Dictionary或者如果您有一個(gè)唯一的項(xiàng)目列表要添加,則從扁平化的項(xiàng)目中創(chuàng)建一個(gè)散列集ITEMS以加快檢查速度。

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
向類中添加遞歸方法,如下所示:
//using System.Linq;
public class ABC
(
string itemName{get;set;}
int parentID{get;set;}
List<ABC> Child {get;set;}
public bool AlreadyContains(ABC abc)
{
if (Child.Any( a => a.itemName == abc.itemName )) return true; //Check children
return Child.Any( a => a.AlreadyContains(abc) ); //Ask children to check their children too
}
)
然后你可以用一行代碼檢查:
if (!abc.AlreadyContains(newAbc)) abc.Add(newAbc);
注意:上面的例子假設(shè)當(dāng)它們的 itemNames 相等時(shí) abc 實(shí)例是相等的。當(dāng)然,您可以修改條件,例如abc.Equals(newAbc)您是否已經(jīng)覆蓋了 Equals(),或者abc == newAbc如果您想要引用相等。
- 2 回答
- 0 關(guān)注
- 201 瀏覽
添加回答
舉報(bào)