存在一个类型为“ book”的值的列表,并且存在一个类型为“ book”的对象。仅在过程中,函数执行之前的图纸和对象的类型是未知的。当使用“ indexOf()”方法时,它给出的索引是-1,而不是3(当用“ book”类型对纸张和对象进行刚性键入时进行检查)。按照惯例,我只有一个裸叶和一个裸对象,没有属性和变量。仅在执行后,对象才能获取类型和值。进行中。那就是整个困难 有什么收获?
//Object with id = 4, has index 3 in the list
obj = Connector.Get(CurrentTable, "WHERE Id = " + id).FirstOrDefault();
//list with 10 records
var list = Connector.Get(CurrentTable, Condition).ToList();
//Need get 3, got -1
var currIndex = list.IndexOf(obj);
var nextIndex = (currIndex < list.Count - 1 ? currIndex : -1) + 1;
var prevIndex = (currIndex > 0 ? currIndex : list.Count) - 1;
ViewBag.NextPost = list[nextIndex];
ViewBag.PrevPost = list[prevIndex];
答案 0 :(得分:1)
它正在比较对象引用。除了直接相等之外,您还必须做其他事情。您可以比较Id属性或其他属性以确定它们是否相等吗?
//Object with id = 4, has index 3 in the list
obj = Connector.Get(CurrentTable, "WHERE Id = " + id).FirstOrDefault();
//list with 10 records
var list = Connector.Get(CurrentTable, Condition).ToList();
var currIndex = list
.Select((a, i) => new {element = a, index = i})
.First(a => a.element.Id == obj.Id)//or some other comparison that you would define as equal
.index;
var nextIndex = (currIndex < list.Count - 1 ? currIndex : -1) + 1;
var prevIndex = (currIndex > 0 ? currIndex : list.Count) - 1;
ViewBag.NextPost = list[nextIndex];
ViewBag.PrevPost = list[prevIndex];
答案 1 :(得分:0)
如果您有任何种类的列表,例如这样的...
var list = Connector.Get(CurrentTable, Condition).ToList();
您可以像这样将列表限制为“ book”类型的对象:
var books = list.OfType<book>().ToList();
过滤它也会强制转换它,因此您可以轻松比较属性。如果class book
具有属性Id
,并且您正在搜索与obj
相匹配的书,则可以执行以下操作:
var foundBook = books.First( b => b.Id == obj.Id );