给定两个 相同大小的IEnumerable s ,如何将其转换为 Dictionary 使用Linq?
IEnumerable<string> keys = new List<string>() { "A", "B", "C" };
IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C" };
var dictionary = /* Linq ? */;
Run Code Online (Sandbox Code Playgroud)
而预期的产出是:
A: Val A
B: Val B
C: Val C
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一些简单的方法来实现它.
我应该担心表现吗?如果我有大量收藏怎么办?
如果有更简单的方法,我不会这样做,目前我这样做:
我有一个Extension方法,它将循环IEnumerable提供元素和索引号.
public static class Ext
{
public static void Each<T>(this IEnumerable els, Action<T, int> a)
{
int i = 0;
foreach (T e in els)
{
a(e, i++); …Run Code Online (Sandbox Code Playgroud) 我知道一般空列表比NULL更喜欢.但我将返回NULL,主要有两个原因
??之后很容易执行操作以获得返回值.对于字符串,我们有IsNullOrEmpty.有没有C#本身为List或IEnumerable做同样的事情?
有没有一种很好的方法将IEnumerable转换为DataTable?
我可以使用反射来获取属性和值,但这似乎有点低效,是否有内置的东西?
(我知道这些例子:ObtainDataTableFromIEnumerable)
编辑:
这个问题通知我处理空值的问题.
我在下面写的代码正确处理空值.
public static DataTable ToDataTable<T>(this IEnumerable<T> items) {
// Create the result table, and gather all properties of a T
DataTable table = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Add the properties as columns to the datatable
foreach (var prop in props) {
Type propType = prop.PropertyType;
// Is it a nullable type? Get the underlying type
if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
propType = new NullableConverter(propType).UnderlyingType;
table.Columns.Add(prop.Name, propType);
}
// …Run Code Online (Sandbox Code Playgroud) 其中一个扩展方法IEnumerable<T>是.AsEnumerable().此方法将其调用的可枚举对象转换为实例IEnumerable<T>.但是,由于对象必须实现IEnumerable<T>才能应用于此扩展方法,因此转换为IEnumerable<T>简单的转换方法IEnumerable<T>.我的问题是为什么这种方法存在?
例:
List<string> strings = new List<string>() { "test", "test2", "test3" };
IEnumerable<string> stringsEnum1 = strings.AsEnumerable();
IEnumerable<string> stringsEnum2 = (IEnumerable<string>)strings;
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,stringsEnum1并且stringsEnum2是等价的.扩展方法有什么意义?
编辑:作为推论,为什么.AsQueryable()在施法时有一种方法IQueryable<T>是等价的?
我想知道IQueryable,List,IEnumerator和我何时应该使用每个的区别?
例如,当使用Linq to SQL时,我会做这样的事情:
public List<User> GetUsers()
{
return db.User.where(/* some query here */).ToList();
}
Run Code Online (Sandbox Code Playgroud)
现在我想知道我是否应该使用IQueryable.我不确定在列表中使用它的好处.
IEnumerable中是否允许索引是否有任何特定原因.
我找到了解决问题的方法,但只是想知道它为什么不允许索引.
谢谢,
我想在.NET 3.5中做这样的事情.什么是最快的方式?
IEnumerable<DataRow> collection =
TypedDataSet.TypedTableBase<DataRow>.Rows as IEnumerable<DataRow>;
Run Code Online (Sandbox Code Playgroud) 通过阅读类似的帖子,我了解到List是一种IEnumerable.但我真的很想知道这两者之间的实际区别是什么.
对于总是使用List并且从未使用IEnumerable的人:
这是一个实际的例子:我们想要存储四个字符串,按字母顺序排序,将它们传递给另一个函数,然后向用户显示结果.我们会用什么?为什么?
希望有人可以为我排序或指出我正确的方向.提前致谢!
为什么我不能使用带有参数的IEnumerable?这会被解决吗?我真的希望他们能重写旧库以使用泛型......
ienumerable ×10
c# ×9
.net ×4
linq ×4
generics ×2
list ×2
.net-3.5 ×1
datatable ×1
dictionary ×1
iqueryable ×1
params ×1