如何访问自定义类型通用列表中的变量?

时间:2020-08-17 18:37:09

标签: c# unity3d

我有一个HashSet<T>,一个List<T>和一个班级。

Relayhash包含一组Vector3变量。用作输入列表,通常会随机或通过另一条规则选择一个变量。

tempList临时存储vector3变量以进行比较。

BuiltList包含一组自定义类类型,用作所选变量的目标。在这里,我想了解它是否包含某个变量(posv3)。

HashSet<Vector3> relayhash = new HashSet<Vector3>();
List<Vector3> tempList = new List<Vector3>();
public List<moduleClass> BuildList = new List<moduleClass>(); 


  public class moduleClass
{
    public int step { get; set; }
    public int modID { get; set; }
    public string modType { get; set; }
    public int typeint { get; set; }
    public Vector3 posv3 { get; set; }
}

我想找出relayhash是否包含BuildList中已经存在的向量。如果为true,则需要从“ relayHash”中删除找到的Vector3(s)。

这些是我尝试过的一些脚本:

 Vector3 tempvar =  moduleClass.posv3; // ClassName.VariableName does not work, why?

foreach (Vector3 tempv3 in relayhash)// 
{
moduleClass tempvar = new moduleClass();
if (BuildList.Contains(tempvar.tempv3))// not accepted, 'does not contain a definition..)
{// do something}
}

foreach (Vector3 tempv3 in relayhash)// 
        {
            moduleClass tempvar = new moduleClass();
            Vector3 tempv = tempvar.posv3;
            tempv = tempv3;

            if (BuildList.Contains(tempv)):// but, cannot convert from 'UnityEngine.Vector3' to 'mods.moduleClass'
            {
                //   var tempvar = new moduleClass(posv3);
                //  tempList.Add(tempv3);
            }
        }

上面的示例有很多变体,但是我看不到树木的森林。尽管查找并尝试了许多类似的示例变体,但我的语法仍不正确。

所以我的问题是:如何访问自定义类型列表中的变量(并与另一个列表中的相同类型进行比较)?

感谢您的光临。

ps:

主要问题在于,现在无法从“ relayhash”中删除找到的Vector。例如:

var foundVectors = relayhash.Intersect(BuildList.Select(x => x.posv3));

relayhash.Remove(foundVectors);

结果:

error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<UnityEngine.Vector3>' to 'UnityEngine.Vector3'

1 个答案:

答案 0 :(得分:0)

我想知道'relayhash'是否包含一个已经在'BuildList'中的Vector。

更具体地说,您想查看relayhash是否包含Vector3 等于posv3 BuildList值的{em >。这是否有助于了解查询的结构?

您可以在任一列表中使用Any,但是由于relayhash已经是HashSet,可以进行便宜的Contains检查,因此,更有效的方法是使用{ {1}}在自定义对象列表上:

Any

如果您想捕获实际的对象,那么bool found = BuildList.Any(x => relayhash.Contains(x.posv3)); 可能更合适:

Where

然后您可以从过滤器列表中捕获v3项目:

var foundItems = BuildList.Where(x => relayhash.Contains(x.posv3));

或执行var foundVectors = foundItems.Select(x => x.posv3);

Intersect