c#generic for aceach to n ienumerable的不明类型
我正在尝试编写一个通用的静态函数,该函数将使用IEnumerable类的实例,属性的名称和字符串分离器。它将循环遍历实例,并在实例的每个成员中评估属性,收集在分隔器间隔的单个字符串中返回的值。
例如,如果我的收藏类包含人的实例,并且属性名称为“姓氏”,而我的分隔符为“','”,我可能会返回:“史密斯','kleine','beecham”。然后,我可能会用单个引号包围它,然后将其用作SQL中的列表。
我的问题是我无法弄清楚如何迭代ienumerable。到目前为止,我的代码是:
public static string EnumerableItem2Str<T>(IEnumerable<T> oItems, string cPropertyName, string cSep)
{
string cOP = "";
try
{
foreach (<T> oItem in oItems)
{
cOP += CoreHelper.GetPropertyValue(oItems, cPropertyName).ToString();
if (oItem != oItems.Last()) cOP += cSep;
}
return cOP;
}
catch (Exception ex)
{
return "";
}
}
public static object GetPropertyValue(object o, string cPropertyName)
{
return o.GetType().GetProperty(cPropertyName).GetValue(o, null);
}
我在 foreach(&lt; t&gt; oitem)上遇到错误的错误。
如何迭代oitems
以获取其中包含的每个实例?
I'm trying to write a generic static function that takes an instance of an IEnumerable class, the name of a property of and a string separator. It will loop through the instance and with each member of the instance evaluate the property, collecting the values returned in a single string spaced by the separator.
For example, if my collection class contains instances of Person and the property name is "Surname", and my separator is "', '", I might return: "Smith', 'Kleine', 'Beecham". I might then surround it in single quotes and use it as a list in SQL.
My problem is that I can't figure out how to iterate over IEnumerable. My code so far:
public static string EnumerableItem2Str<T>(IEnumerable<T> oItems, string cPropertyName, string cSep)
{
string cOP = "";
try
{
foreach (<T> oItem in oItems)
{
cOP += CoreHelper.GetPropertyValue(oItems, cPropertyName).ToString();
if (oItem != oItems.Last()) cOP += cSep;
}
return cOP;
}
catch (Exception ex)
{
return "";
}
}
public static object GetPropertyValue(object o, string cPropertyName)
{
return o.GetType().GetProperty(cPropertyName).GetValue(o, null);
}
I get errors on the line foreach (<T> oItem in oItems)
the first of which is "type expected" on <T>
.
How do I iterate over oItems
to get each instance contained within it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以这样做:
检查它在这里
You can do this:
Check it here
我认为您想做这样的事情(它确实具有无效的促进检查,因此,如果您使用的是C#的旧版本,则需要在“ .getValue(i)”之前删除该问号:
I think you want to do something like this (it does have a null propogation check so if you're using an old version of C# then you'll need to remove that question mark before the '.GetValue(i)'):