【发布时间】:2018-03-20 18:55:56
【问题描述】:
您好,我只是想在将一些旧的 Javascript 代码重写为 C# 之前让结构正确。
我有一个 CanDetails 列表,我需要能够在其中搜索 ByteName 并获取其 BytePos 值。
我正在为能够使用我的 linqQuery 提取 BytePos 的查询而苦苦挣扎,我希望只有在可能的情况下才能获得返回的整数值。
我在 LinQ 上的尝试简化了下面的示例。
问题是我在结果中返回了一个 CanDetails 对象,但仍需要在其中再次搜索以找到我正在寻找的 BtyePos。
非常感谢。
public class ByteData
{
public string ByteName { get; set; }
public int BytePos { get; set; }
}
public class CanDetails
{
public string CanName { get; set; }
public int CanID { get; set; }
public List<ByteData> ByteStuff { get; set; }
public int[] RawData { get; set; }
}
public class test
{
public static void Main()
{
List<CanDetails> CanIDs = new List<CanDetails>();
CanIDs.Add(new Models.CanDetails()
{
CanName = "test",
CanID = 11,
ByteStuff = new List<ByteData>() {
new ByteData { ByteName = "james", BytePos = 0 },
new ByteData { ByteName = "bob", BytePos = 1 },
},
RawData = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 }
});
var linqQuery = CanIDs.Where(o => o.ByteStuff.Any(x => x.ByteName == "james")).Select(x => x.ByteStuff).First();
}
}
【问题讨论】:
-
这段代码有什么问题?它有任何错误吗?你得到什么意想不到的输出?你期待什么输出?
-
@ChetanRanpariya 代码有效,但我无法在 CanID 中的 ByteName 上运行 Linq 查询搜索并返回找到的 BytePosition。最后一行 Var linqQuery 是我苦苦挣扎的地方。
-
它有什么错误吗?您在
linqQuery中获得了什么价值? -
@SamIam 将返回一个 CanDetails 对象,我仍然需要搜索该对象以找到针对 ByteName 进行初始搜索的 BytePos
-
这可能不是最优雅的方式,但它似乎有效:
var linqQuery = CanIDs.Select(o => o.ByteStuff.Where(x => x.ByteName == "james")).First().First().BytePos;
标签: c# list linq asp.net-mvc-5