C# 想要使用方法从foreach返回列表并返回所有项,但我得到:(集合)
因此,基本上,当按钮上发生click事件以检查字符串是否匹配时,会触发该方法:C# 想要使用方法从foreach返回列表并返回所有项,但我得到:(集合),c#,error-handling,C#,Error Handling,因此,基本上,当按钮上发生click事件以检查字符串是否匹配时,会触发该方法: lbPlaylist.Items.Add(o.GetFragment(tbTitle.Text)); } 该方法的代码为: public List<SoundFragment> GetFragment(String p) { List<SoundFragment> list1 = new List<SoundFragment>
lbPlaylist.Items.Add(o.GetFragment(tbTitle.Text));
}
该方法的代码为:
public List<SoundFragment> GetFragment(String p)
{
List<SoundFragment> list1 = new List<SoundFragment>();
//make a list and store every string
foreach(SoundFragment i in fragments)
{
if (i.Title.Contains(p))
{
list1.Add(i);
}
}
//return all the objects from the new list that stores all the string contained in the fragments list
return list1;
}
public List GetFragment(字符串p)
{
List list1=新列表();
//制作一个列表并存储每个字符串
foreach(片段中的声音片段i)
{
如果(i.标题包含(p))
{
清单1.添加(i);
}
}
//从存储片段列表中包含的所有字符串的新列表中返回所有对象
返回列表1;
}
问题是我真的将对象或对象集合返回到列表框,我只想返回添加的字符串名称。如何访问它们?如果只想返回字符串列表中的对象名称,请尝试以下操作
public List<string> GetFragment(String p)
{
List<SoundFragment> list1 = new List<SoundFragment>();
List<string> result = new List<string>();
//make a list and store every string
foreach(SoundFragment i in list1)
{
if (i.Title.Contains(p))
{
result.Add(i.Title);
}
}
//return all the objects from the new list that stores all the string contained in the fragments list
return result ;
}
public List GetFragment(字符串p)
{
List list1=新列表();
列表结果=新列表();
//制作一个列表并存储每个字符串
foreach(列表1中的声音片段i)
{
如果(i.标题包含(p))
{
结果。添加(i.标题);
}
}
//从存储片段列表中包含的所有字符串的新列表中返回所有对象
返回结果;
}
除了Richard的答案,你的主要问题是那句话:
lbPlaylist.Items.Add(o.GetFragment(tbTitle.Text));
在这里,您可以将整个集合作为一个项目添加到列表框中。你必须使用
lbPlaylist.Items.AddRange(o.GetFragment(tbTitile.Text).ToArray());
将每个对象作为单个项添加
然后,ListBox
将使用集合中对象的ToString()
方法显示每个对象的文本。如果您的SoundFragment
实现了适合您需要的ToString()
方法,那么一切都可以正常工作。否则,您必须将GetFragment
方法修改为Richard建议的方式。您将返回集合定义为片段集合。显然,您必须向其中添加对象。请提供一个您希望得到的示例对象。目前尚不清楚当前代码为何不适用于您。您在listview中看到的是System.Collection
,因为您正在将列表添加到lbPlaylists.Items
。我猜您希望迭代所有返回的SoundFragment
sGetFragment()
函数返回并将它们分别添加到lbPlaylists.Items
?为什么不更改方法签名以返回列表或字符串呢?如果我们可以看到SoundFragment
的样子,这也会有所帮助。.是的,我正在返回列表集合,但我想访问列表集合以从这些对象中获取其中一个它们已经分配的属性:string name,这样我就可以将它们全部作为字符串而不是对象添加到列表框中。该方法返回一个充满对象的列表,我只需要这些对象的一个实例,但它不允许我像列表1那样做。标题或诸如此类的东西为什么你要迭代一个空列表list1
?已经尝试过了,但是创建一个新列表不起作用,因为foreach会迭代SoundFragment,它是一个列表对象而不是字符串。列表不是空的,我不知道如何访问从类调用的列表中的对象实例:DYou只能提取SoundFragment对象的标题,标题是一个字符串,您可以将所有对象添加到一个新列表中,然后返回