C# 奇怪?发布列表的演员阵容<;T>;排列
我已经定义了列表C# 奇怪?发布列表的演员阵容<;T>;排列,c#,arrays,list,C#,Arrays,List,我已经定义了列表 private class Kamery { public int iIndeks; public string strNazwa; public Kamery(int Indeks, string Nazwa) { iIndeks = Indeks; strNazwa = Nazwa; } } List<Kamery&
private class Kamery
{
public int iIndeks;
public string strNazwa;
public Kamery(int Indeks, string Nazwa)
{
iIndeks = Indeks;
strNazwa = Nazwa;
}
}
List<Kamery> lKamery = new List<Kamery>();
但编译器表示无法将类型“char[]”转换为“string”
为什么?需要如何执行?我认为您的问题在于。Find只返回1个值,即列表中的第一个匹配项。 此值将是一个字符串,通过使用.toArray,您将该字符串转换为char[],然后尝试将其转换回字符串 我不太擅长c#,所以一般的解决方案是:
声明数组,执行foreach,每次id匹配时,将名称放入数组并包含索引。这在某种程度上限制了它,因为您必须有一个固定的大小,使用列表可能会更好。我认为您的问题在于。Find只返回1个值,即列表中的第一个匹配项。 此值将是一个字符串,通过使用.toArray,您将该字符串转换为char[],然后尝试将其转换回字符串 我不太擅长c#,所以一般的解决方案是: 声明数组,执行foreach,每次id匹配时,将名称放入数组并包含索引。这在某种程度上限制了它,因为您必须有一个固定的大小,使用列表可能会更好。我想您需要:
string[] strNazwa = lKamery.Where(item => item.iIndeks == iIndeks)
.Select(item => item.strNazwa)
.ToArray();
这将为您提供一个字符串数组,其中包含满足Where
条件的项目列表中的每个strNazwa
值
下面是您的原始代码所做的:
string[] strNazwa = (string)
// get the one item that matches the condition
lKamery.Find(item => item.iIndeks ==Indeks)
// get the strNazwa property from that one item
.strNazwa
// return the string as a char array
.ToArray();
当您尝试将char[]
强制转换为string
时,它会失败,因为您无法强制转换它。您可以从字符数组创建字符串,但不能通过强制转换。我想您需要:
string[] strNazwa = lKamery.Where(item => item.iIndeks == iIndeks)
.Select(item => item.strNazwa)
.ToArray();
这将为您提供一个字符串数组,其中包含满足Where
条件的项目列表中的每个strNazwa
值
下面是您的原始代码所做的:
string[] strNazwa = (string)
// get the one item that matches the condition
lKamery.Find(item => item.iIndeks ==Indeks)
// get the strNazwa property from that one item
.strNazwa
// return the string as a char array
.ToArray();
当您尝试将
char[]
强制转换为string
时,它会失败,因为您无法强制转换它。您可以从字符数组创建字符串,但不能通过强制转换。它是哪种语言?strNazwa
是一个字符串,它是一个IEnumerable
,因此strNazwa.ToArray()
返回一个字符数组,而不是字符串。很难判断您想要的输出是什么。您是否使用源中与条件匹配的每个strNazwa
数组?或者您想要一个数组,该数组的值来自与条件匹配的一项?它是哪种语言?strNazwa
是一个字符串,它是一个IEnumerable
,因此strNazwa.ToArray()
返回一个字符数组,而不是字符串。很难判断您想要的输出是什么。您是否使用源中与条件匹配的每个strNazwa
数组?或者您想要一个数组,该数组的值来自与条件匹配的一个项?除非OP使用所需的输出进行应答,否则这就足够了。除非OP使用所需的输出进行应答,否则这就足够了。