linq find in which position is my object in List [duplicate]

若如初见. 提交于 2019-12-11 10:33:16

问题


kriteriji is type of List<Kriteriji>

var doc = kriteriji.Where(k => k.Ean == txtEan.Text
                     && k.PredmetObravnave == acPredmetObravnave.Text
                     && k.Tse == txtTse.Text
                     && k.DejanskaKolicina == Convert.ToInt32(txtKolicina.Text)
                     && k.KratekNazEnoteMere == acKNEnotaMere.Text
                     && k.OznakaLokacije == acOznakaLokacije.Text
                     && k.OznakaZapore == txtZapora.Text
                     && k.SarzaDob == txtSarzaDobavitelja.Text
                     && k.Sarza == txtSarza.Text
                     && k.DatumVelOd == datumOd
                     && k.DatumVelDo == datumDo).FirstOrDefault();

Now when I get doc how can I know in which position in List<kriteriji> is? I need to now if is in first, second,...


回答1:


Use the IndexOf method:

kriteriji.IndexOf(doc);



回答2:


I think you could create a (index , value) keyvaluepaire object at first and then retrive it like

        var doc = kriteriji.Select((value, index) => new { index, value })
            .Where(k => k.value.Ean == txtEan.Text
                 && k.value.PredmetObravnave == acPredmetObravnave.Text
                 && k.value.Tse == txtTse.Text
                 && k.value.DejanskaKolicina == Convert.ToInt32(txtKolicina.Text)
                 && k.value.KratekNazEnoteMere == acKNEnotaMere.Text
                 && k.value.OznakaLokacije == acOznakaLokacije.Text
                 && k.value.OznakaZapore == txtZapora.Text
                 && k.value.SarzaDob == txtSarzaDobavitelja.Text
                 && k.value.Sarza == txtSarza.Text
                 && k.value.DatumVelOd == datumOd
                 && k.value.DatumVelDo == datumDo).FirstOrDefault();

then you could get the index like

Console.WriteLine(doc.index);



回答3:


You can use an overload for select that will take an index and a Kriteriji.

Here is the documentation.

Then you could select an anonymous object with an Index property and a Doc property. If you would use IndexOf this will cause another search throughout the list while you already have that data.




回答4:


Try this:

var position = kriteriji.IndexOf(doc);



回答5:


You can find out the index with:

kriteriji.IndexOf(doc.First());


来源:https://stackoverflow.com/questions/8209197/linq-find-in-which-position-is-my-object-in-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!