首页 > 解决方案 > 如何在 Protobuf 重复字段中进行搜索?

问题描述

这是我第一次使用 protobuf,我想知道是否有任何方法可以访问重复字段中的某个项目。

我创建了一个方法,它将遍历所有项目,检查项目字段并返回它(我无法返回指向它的指针:()。

public Appearance findItem(int itemID) {
  foreach (Appearance item in appearances.Object) {
    if (item.Id == itemID) {
      return item;
    }
  }
  return null;
}

似乎没有使用某些 lambda 表达式的 find 方法。

有没有其他方法可以实现这一目标?如果我可以有指向该项目的指针,而不是它的副本,那将是完美的,所以如果我改变它,我可以直接写完整的重复字段。

标签: c#protobuf-csharp-port

解决方案


如果我可以有指向该项目的指针,而不是它的副本,那将是完美的,所以如果我改变它,我可以直接写完整的重复字段。

你不能这样做,但你可以返回元素的索引。鉴于重复字段实现IEnumerable<T>,您应该能够足够轻松地使用 LINQ。例如:

// index is an "int?" with a value of null if no items matched the query
var index = repeatedField
    // You could use tuples here if you're using C# 7. That would be more efficient.
    .Select((value, index) => new { value, (int?) index })
    // This is whatever condition you want
    .Where(pair => pair.value.SomeField == "foo")
    .Select(pair => pair.index)
    .FirstOrDefault();

推荐阅读