我正在尝试编写一个通用静态函数,它接受IEnumerable类的实例、属性的名称和字符串分隔符。它将遍历实例,并与实例的每个成员一起计算属性,收集在分隔符间隔的单个字符串中返回的值。
例如,如果我的集合类包含Person的实例,而属性名是“姓氏”,而我的分隔符是"',‘'",我可能会返回:“Smith”,'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 (<T> oItem in oItems)上得到了错误,第一个错误是<T>上的“类型预期”。
如何在oItems上迭代以获得包含在其中的每个实例?
发布于 2022-05-07 10:32:43
我认为您希望这样做(它确实具有空传递检查,所以如果您使用的是旧版本的C#,则需要在“.GetValue(I)”之前删除该问号):
public static string EnumerableItem2Str<T>(IEnumerable<T> oItems, string cPropertyName, string cSep)
{
var propertyValues = oItems
.Select(i => i.GetType().GetProperty(cPropertyName)?.GetValue(i))
.Where(v => v != null)
.ToList();
return string.Join(cSep, propertyValues);
}发布于 2022-05-07 10:27:49
你可以这样做:
static string GetCsv<T>(IEnumerable<T> items, string separator)
{
return String.Join(separator, items.Select(x => x.ToString()).ToArray());
}检查它,这里
https://stackoverflow.com/questions/72151530
复制相似问题