3 回答

TA貢獻1818條經驗 獲得超8個贊
以下代碼應該快得多,因為它使用散列而不是嵌套循環:
// build a HashSet of your key's type (I'm assuming integers here) containing all your current elements' keys in the _nodes ObservableCollection
HashSet<int> hashSet = new HashSet<int>(_nodes.Select(n => n.ID));
foreach (var l in seznamVlaku.SelectMany(s => s.ProjizdejiciStanicemi)) {
// if you can add the element's ID to the HashSet it hasn't been added before
if(hashSet.Add(l.Key.ID)) {
_nodes.Add(new Node() {Name = l.Key.Jmeno, ID = l.Key.ID, X = l.Key.X, Y = l.Key.Y });
}
}

TA貢獻1818條經驗 獲得超3個贊
我不認為這是一個很大更快的方式,你必須檢查是否l已經存在_nodes,而且每個l。如果你能在更高的層次上優化它,我不知道這是在做什么。
如果你只是想要一個更短的 LINQ 語句,你可以使用SelectMany:
foreach(var l in sznamVlaku.SelectMany(s => s.ProjizdejiciStanicemi)
.Where(x => _nodes.All(a => a.ID != x.Key.ID)))
_nodes.Add(new Node() {Name = l.Key.Jmeno, ID = l.Key.ID, X = l.Key.X, Y = l.Key.Y });
請注意,我用All的不是Any,因為你想找到的所有l地方的所有節點都有一個不同的ID。

TA貢獻1963條經驗 獲得超6個贊
你不需要兩個foreach。而是使用 SelectMany。
你的例子:
foreach (var p in seznamVlaku.Select(s => s.ProjizdejiciStanicemi))
{
foreach (var l in p)
{
}
}
我們可以這樣寫,結果是一樣的:
foreach (var node in seznamVlaku.SelectMany(list => list.ProjizdejiciStanicemi))
{
}
您可以將條件(現有項目)添加到 linq 查詢的管道中
代碼:
foreach (var node in seznamVlaku
.SelectMany(list => list.ProjizdejiciStanicemi)
.Where(item => nodes
.Exists(node => node.ID != item.ID)))
{
_nodes.Add(new Node() {Name = node.Key.Jmeno, ID = node.Key.ID, X = node.Key.X, Y = node.Key.Y });
}
- 3 回答
- 0 關注
- 289 瀏覽
添加回答
舉報