我有一个类,里面有一个列表集合。我想在其中一个列表中搜索一个参数。所以我找到了列表的位置,我希望在同一个班级的其他列表中找到相同的位置...
如何实现这一目标?
void Main()
{
var myListCollectionObj = new myListCollection();
Console.WriteLine(myListCollectionObj.firstList);
Console.WriteLine(myListCollectionObj.secondList);
Console.WriteLine(myListCollectionObj.thirdList);
var testFirstList = myListCollectionObj.firstList.Where(x => x == 3); //then i want to get "33", and 333 from secondList and thirdList respectively
Console.WriteLine(testFirstList);
}
class myListCollection
{
public List<int> firstList = new List<int>(){ 1, 2, 3, 4, 5};
public List<string> secondList = new List<string>(){ "11", "22", "33", "44", "55"};
public List<int> thirdList = new List<int>(){ 111, 222, 333, 444, 555};
}
答案 0 :(得分:3)
int index = myListCollectionObj.firstList.IndexOf(3);
string elem2;
int elem3;
if (index >= 0 && index < myListCollectionObj.secondList.Length)
elem2 = myListCollectionObj.secondList[index]
if (index >= 0 && index < myListCollectionObj.thirdList.Length)
elem3 = myListCollectionObj.thirdList[index]
答案 1 :(得分:1)
您不需要LINQ,只有class User < ApplicationRecord
devise :timeoutable, :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable, :validatable, :omniauthable, :confirmable
end
自己的List<T>
方法和索引器属性:
IndexOf()
您可能希望添加错误处理:如果int index = myListCollectionObj.firstList.IndexOf(3);
string secondValue = myListCollectionObj.secondList[index];
int thirdValue = myListCollectionObj.thirdList[index];
中未包含3
,则firstList
会返回-1
的索引。
答案 2 :(得分:1)
如果有多个3
值,我认为最好的方法是使用简单的for
循环:
var testFirstList = new List<int>();
var testSecondList = new List<string>();
var testThirdList = new List<int>();
for (var i = 0; i < myListCollectionObj.firstList.Length; ++i) {
if (myListCollectionObj.firstList[i] == 3) {
testFirstList.Add(myListCollectionObj.firstList[i]);
testSecondList.Add(myListCollectionObj.secondList[i]);
testThirdList.Add(myListCollectionObj.thirdList[i]);
}
}
答案 3 :(得分:1)
一个好的指导方针是,如果你发现自己将索引和LINQ结合起来,你可能还有其他选择。在这种情况下,一个好的选择是使用Zip
此方法允许您将3个集合组合在一起,并将生成的压缩集合作为单个实体进行操作,以便不再直接需要索引。
var result = firstList.Zip(
secondList.Zip(thirdList,
(b, c) => new { b, c }),
(a, b) => new { Value1 = a, Value2 = b.b, Value3 = b.c })
.Where(x => x.Value1 == 3).ToList();
result.ForEach(v => Console.WriteLine(v));
答案 4 :(得分:0)
纠正我,如果我错了你在第一个列表中查找你搜索的项目的索引,然后使用相同的索引从其他列表中检索
如果是的话 试试这个
var testFirstList = myListCollectionObj.firstList.Where(x => x == 3).FirstOrDefault(); //then i want to get "33", and 333 from secondList and thirdList respectively
var index = myListCollectionObj.firstList.IndexOf(testFirstList);