我需要根据存储在列表中的对象的特定属性构建一个csv字符串,但我必须为多个属性执行此操作:
当"硬编码":
时,以下工作正常var list = customers.Select(p => p.Email).ToArray();
csvString = string.Join(";", list1);
但我显然不想为我需要的每件房产做这件事。有没有办法让我构建一个函数并将我想要使用的属性名称分配给其中一个参数。类似的东西:
var emails = ConvertCollectionToCsv(customers, "Email");
var names = ConvertCollectionToCsv(customers, "Name");
var mobile = ConvertCollectionToCsv(customers, "Mobile");
...
我想我会尝试以下方法:
private string ConvertCollectionToCsv(List<Customer> customers, string propertyName)
{
var prop = typeof(EmailAddress).GetProperties().FirstOrDefault
(p => p.Name.ToLowerInvariant() == propertyName.ToLowerInvariant());
var list = customers.Select(p => prop.Name).ToArray();
return string.Join(";", list);
}
但被召唤时:
var emails = ConvertCollectionToCsv(customers, "Email");
它返回电子邮件;电子邮件;电子邮件而不是使用prop.Name时有意义的电子邮件地址。我尝试使用GetValue:
var list = customers.Select(p => prop.GetValue(p)).ToArray();
但是这引发了以下错误:
"Object does not match target type."
有什么建议吗?
由于
答案 0 :(得分:0)
您必须从客户处获取属性,因为您以后会获得该值。
var prop = typeof(Customer).GetProperties().FirstOrDefault
(p => p.Name.ToLowerInvariant() == propertyName.ToLowerInvariant());
这看起来很奇怪:
var list = list.Select(p => prop.GetValue(p)).ToArray();
list.Select - 什么是列表? 并非如此:
var list = customers.Select(p => prop.GetValue(p)).ToArray();
答案 1 :(得分:0)
您正在将var CACHE_NAME = 'cache-v2';
var urlsToCache = [
'/assets/css/app.css',
'/assets/js/main.js',
'/assets/js/other.js'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== CACHE_NAME) {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function(response) {
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
- 对象列表传递给方法,但使用的属性为Customer
,这些类型不匹配。
我建议使用通用方法:
EmailAddress
这样,您可以传入任何集合,例如private string ConvertCollectionToCsv<T>(IEnumerable<T> items, string propertyName)
{
var prop = typeof(T).GetProperties().FirstOrDefault
(p => p.Name.ToLowerInvariant() == propertyName.ToLowerInvariant());
var list = items.Select(p => prop.GetValue(p)).ToArray();
return string.Join(";", list);
}
或List<string>