I have this class
public class MyViewModel {
public MyClass Thing { get; set; }
public int Id { get { return Thing.Id; } }
public string Name { get { return Thing.Name; } }
}
I noticed when I bind it to an ASP.NET GridView, it automatically omits Thing
, and for a good reason (ie. because otherwise it will only show the meaningless "MyNamespace.MyClass" in all rows)
I am trying to do a similar thing in this method.
public static string ConvertToCsv<T>(IEnumerable<T> items)
{
foreach (T item in items)
{
if(item is not a native/.NET class) // <-- How do you do this?
continue;
else // If it is a string/int/bool/DateTime or something meaningful
{
...
}
}
}
Not sure about performance, but you could use somthing along the lines of
if(item.GetType().Namespace.StartsWith("System"))
{
// do stuff
}
Or filter before looping
public static string ConvertToCsv<T>(IEnumerable<T> items)
{
foreach (T item in items.Where(i => i.GetType().Namespace.StartsWith("System")))
{
}
}
Edit: after a quick test the method above has some flaws, If your object is nullable (MyViewModel?) it will be picked up in this check (System.Nullable<MyViewModel>
).
So perhaps you could use:
public static string ConvertToCsv<T>(IEnumerable<T> items)
{
foreach (T item in items.Where(i => i.GetType().Module.ScopeName.Equals("CommonLanguageRuntimeLibrary")))
{
}
}
Another edit: There seems to be some issue with the last method also, But this one below is by far the fastest and most reliable, We just create a list of the System.Objects from the Assembly, and check if your item object is in that list.
private List<Type> _systemTypes;
public List<Type> SystemTypes
{
get
{
if (_systemTypes == null)
{
_systemTypes = Assembly.GetExecutingAssembly().GetType().Module.Assembly.GetExportedTypes().ToList();
}
return _systemTypes;
}
}
public static string ConvertToCsv<T>(IEnumerable<T> items)
{
foreach (T item in items.Where(i => SystemTypes.Contains(i.GetType())))
{
// is system type
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With