我正在使用 System.Linq.Dynamic.Core 并尝试使用如下模型运行动态查询:
public class Index
{
public long Position { get; set; }
public object[] Values { get; set; }
}
还有这样的数据样本:
var indexes = new Dictionary<long, Index>();
indexes.Add(1, new Index { Position = 1000, Values = new object[3] { "Welly", "Chandra", Tuple.Create<int, int>(1, 2) } });
indexes.Add(2, new Index { Position = 1001, Values = new object[3] { "Darma", "Angelo", Tuple.Create<int, int>(3, 4) } });
indexes.Add(3, new Index { Position = 1002, Values = new object[3] { "Abby", "Yeremia", Tuple.Create<int, int>(5, 6)} });
indexes.Add(4, new Index { Position = 1003, Values = new object[3] { "Yonathan", "Gunawan", Tuple.Create<int, int>(7, 8)} });
indexes.Add(5, new Index { Position = 1004, Values = new object[3] { "Aldy", "Santoso", Tuple.Create<int, int>(11, 12)} });
var queryable = indexes.Values.AsQueryable();
var result = queryable.Where("Values[1].Equals(\"Yeremia\") || ((Tuple<int, int>) Values[2]).Item2.Equals(8)").ToList();
但它总是抛出异常:
Exception: No property or field 'Tuple' exists in ...
这里查询时不能使用type-casting
吗?
答案 0 :(得分:0)
我不明白你为什么在 linq where 子句中写字符串。
以下是我最后的完整代码。
var indexes = new Dictionary<long, Index>();
indexes.Add(1, new Index { Position = 1000, Values = new object[3] { "Welly", "Chandra", Tuple.Create<int, int>(1, 2) } });
indexes.Add(2, new Index { Position = 1001, Values = new object[3] { "Darma", "Angelo", Tuple.Create<int, int>(3, 4) } });
indexes.Add(3, new Index { Position = 1002, Values = new object[3] { "Abby", "Yeremia", Tuple.Create<int, int>(5, 6) } });
indexes.Add(4, new Index { Position = 1003, Values = new object[3] { "Yonathan", "Gunawan", Tuple.Create<int, int>(7, 8) } });
indexes.Add(5, new Index { Position = 1004, Values = new object[3] { "Aldy", "Santoso", Tuple.Create<int, int>(11, 12) } });
var queryable = indexes.Values.AsQueryable();
var result = queryable.Where(cc=>cc.Values[1].Equals("Yeremia") || ((Tuple<int, int>) cc.Values[2]).Item2.Equals(8)).ToList();
更新:这对我有用。不需要类型转换。
var indexes = new Dictionary<long, Index>();
indexes.Add(1, new Index { Position = 1000, Values = new object[3] { "Welly", "Chandra", Tuple.Create<int, int>(1, 2) } });
indexes.Add(2, new Index { Position = 1001, Values = new object[3] { "Darma", "Angelo", Tuple.Create<int, int>(3, 4) } });
indexes.Add(3, new Index { Position = 1002, Values = new object[3] { "Abby", "Yeremia", Tuple.Create<int, int>(5, 6) } });
indexes.Add(4, new Index { Position = 1003, Values = new object[3] { "Yonathan", "Gunawan", Tuple.Create<int, int>(7, 8) } });
indexes.Add(5, new Index { Position = 1004, Values = new object[3] { "Aldy", "Santoso", Tuple.Create<int, int>(11, 12) } });
var queryable = indexes.Values.AsQueryable();
var result = queryable.Where("Values[1].Equals(\"Yeremia\") || Values[2].Item2.Equals(8)").ToList();