标签: todictionary

将Linq查询结果转换为字典

我想使用Linq to SQL向数据库添加一些行,但我想在添加行之前进行"自定义检查",以了解是否必须添加,替换或忽略进行的行.我希望尽可能降低客户端和数据库服务器之间的流量,并尽量减少查询次数.

为此,我希望获取验证所需的信息,并且只需要在流程开始时获取一次.

我在考虑做这样的事情,但很明显,它不起作用.有人有想法吗?

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj
        select (new KeyValuePair<int, DateTime>(ot.Key, ot.TimeStamp))
    )
Run Code Online (Sandbox Code Playgroud)

我最后想要的是一个Dictionary,而不必从TableObject下载整个ObjectType对象.

我还考虑了以下代码,但我试图找到一个正确的方法:

List<int> keys = (from ObjType ot in TableObj orderby ot.Key select ot.Key).ToList<int>();
List<DateTime> values = (from ObjType ot in TableObj orderby ot.Key select ot.Value).ToList<int>();
Dictionary<int, DateTime> existingItems = new Dictionary<int, DateTime>(keys.Count);
for (int i = 0; i < keys.Count; i++)
{
    existingItems.Add(keys[i], values[i]);
}
Run Code Online (Sandbox Code Playgroud)

c# linq todictionary linq-to-sql

327
推荐指数
3
解决办法
31万
查看次数

将IOrderedEnumerable <KeyValuePair <string,int >>转换为Dictionary <string,int>

我正在关注另一个问题答案,我得到了:

// itemCounter is a Dictionary<string, int>, and I only want to keep
// key/value pairs with the top maxAllowed values
if (itemCounter.Count > maxAllowed) {
    IEnumerable<KeyValuePair<string, int>> sortedDict =
        from entry in itemCounter orderby entry.Value descending select entry;
    sortedDict = sortedDict.Take(maxAllowed);
    itemCounter = sortedDict.ToDictionary<string, int>(/* what do I do here? */);
}
Run Code Online (Sandbox Code Playgroud)

Visual Studio要求参数Func<string, int> keySelector.我尝试了一些我在网上找到并放入的半相关示例k => k.Key,但这会产生编译错误:

'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,int>>' 不包含'ToDictionary'的定义,最好的扩展方法重载 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)'有一些无效的参数

c# linq todictionary

37
推荐指数
2
解决办法
2万
查看次数

如何将KeyValuePair <x,y>的IEnumerable转换为Dictionary?

是否简化了将list/enumberable转换KeyValuePair<T, U>Dictionary<T, U>

Linq转换,.ToDictionary()扩展无效.

linq dictionary todictionary

26
推荐指数
2
解决办法
2万
查看次数

C#ToDictionary lambda选择索引和元素?

我有一个字符串string strn = "abcdefghjiklmnopqrstuvwxyz",想要一个字典,如:

Dictionary<char,int>(){
    {'a',0},
    {'b',1},
    {'c',2},
    ...
}
Run Code Online (Sandbox Code Playgroud)

我一直在尝试这样的事情

strn.ToDictionary((x,i) => x,(x,i)=>i);
Run Code Online (Sandbox Code Playgroud)

...但是我一直在得到关于代表的各种错误,没有采用两个参数,以及未指明的参数等.

我究竟做错了什么?

我更喜欢对答案的提示,所以我对下次需要做的事情有精神上的痕迹,但根据Stackoverflow的性质,答案也很好.

c# lambda delegates anonymous-function todictionary

18
推荐指数
2
解决办法
1万
查看次数

有没有更好的方法来使用LINQ聚合字典?

我试图从可枚举的构建字典,但我需要一个聚合器用于所有可能重复的键.直接使用ToDictionary()偶尔会导致重复键.

在这种情况下,我有一堆时间条目({DateTime Date,double Hours}),如果同一天有多个时间条目,我想要那天的总时间.即,一个自定义聚合器,它将为我提供一个字典条目的唯一键.

有没有比这更好的方法呢?

(这确实有效.)

    private static Dictionary<DateTime, double> CreateAggregatedDictionaryByDate( IEnumerable<TimeEntry> timeEntries )
    {
        return
            timeEntries
                .GroupBy(te => new {te.Date})
                .Select(group => new {group.Key.Date, Hours = group.Select(te => te.Hours).Sum()})
                .ToDictionary(te => te.Date, te => te.Hours);
    }
Run Code Online (Sandbox Code Playgroud)

我想我真的在寻找这样的东西:

IEnumerable<T>.ToDictionary( 
    /* key selector : T -> TKey */, 
    /* value selector : T -> TValue */, 
    /* duplicate resolver : IEnumerable<TValue> -> TValue */ );
Run Code Online (Sandbox Code Playgroud)

所以...

timeEntries.ToDictionary( 
    te => te.Date, 
    te => te.Hours, 
    duplicates => duplicates.Sum() );
Run Code Online (Sandbox Code Playgroud)

'解析器'可以是.First()或.Max()等等.

或类似的东西.


我有一个实现......当我正在研究时,另一个实现了答案.

矿: …

c# linq group-by aggregate todictionary

8
推荐指数
1
解决办法
5427
查看次数

c#ToDictionary with ContainsKey check

我有一个列表,我想放在字典中,为简单起见,插入的值将是相同的.

我可以使用foreach循环.

    List<string> list = new List<string>();
    list.Add("Earth");
    list.Add("Wind");
    list.Add("Fire");
    list.Add("Water");
    list.Add("Water"); // Will NOT BE INSERTED using the foreach loop

    var myDictionary= new Dictionary<string, int>();
    foreach (string value in list)
    {
        if (!myDictionary.ContainsKey(value))
        {
        myDictionary.Add(value, 1);
        }
    }
Run Code Online (Sandbox Code Playgroud)

以上工作.

但我想用ToDictionary以下列方式做同样的事情 -

    Dictionary<string, int> myDictionary2 = list.ToDictionary(i => i, i => 1);
Run Code Online (Sandbox Code Playgroud)

当然这失败了,因为我加了两次"水".

使用ToDictionary时检查重复条目的正确方法是什么?

c# linq lambda dictionary todictionary

8
推荐指数
2
解决办法
9212
查看次数

如何使用Linq ToDictionary返回字典项中具有多个值的字典?

我想从标题下的linq查询中对项目进行分组,这样对于每个标题,我都有一个与标题标题匹配的对象列表.我假设解决方案是使用ToDictionary来转换对象,但是每个"group"(或字典键)只允许一个对象.我假设我可以创建类型字典(String,List Of()),但我无法弄清楚如何编写它.

作为一个例子,我在下面写了一个简化版本.

Public Class order
    Public ID As Integer
    Public Name As String
    Public DateStamp As Date
End Class
Public Function GetOrdersSortedByDate() As Generic.Dictionary(Of String, Generic.List(Of User))
    Dim orders As New List(Of order)(New order() _
    {New order With _
     {.ID = 1, .Name = "Marble", .DateStamp = New Date(2010, 1, 1)}, _
     New order With _
     {.ID = 2, .Name = "Marble", .DateStamp = New Date(2010, 5, 1)}, _
     New order With _
     {.ID = 3, .Name = "Glass", …
Run Code Online (Sandbox Code Playgroud)

linq vb.net delegates todictionary

6
推荐指数
2
解决办法
2万
查看次数

LINQ - 将List <string>转换为Dictionary <string,string>

我正在吃午餐上的Kata,我已经不知所措......

这是我要遵循的步骤:

  • 给定输入字符串,将字符串拆分为新行字符
  • 给定上一步的字符串数组结果,跳过数组中的第一个元素
  • 给定上一步产生的字符串集合,创建一个由每2个元素组成的集合

在最后一个语句中我的意思是,给定4个字符串的集合:

{
    "string1",
    "string2",
    "string3",
    "string4"
}
Run Code Online (Sandbox Code Playgroud)

我应该最终得到这些对的集合('tuples'是正确的术语吗?):

{
    { "string1","string2" },
    { "string3","string4" }
}
Run Code Online (Sandbox Code Playgroud)

我开始查看ToDictionary,然后转移到选择匿名类型,但我不知道如何说"将下两个字符串作为一对返回".

在撰写本文时,我的代码与此类似:

public void myMethod() {

    var splitInputString = input.Split('\n');

    var dic = splitInputString.Skip(1).Select( /* each two elements */ );
}
Run Code Online (Sandbox Code Playgroud)

干杯求救!

詹姆士

linq tuples todictionary

6
推荐指数
1
解决办法
510
查看次数

如何将多维数组转换为字典?

我有一个 n×3 数组,我希望转换为 a Dictionary<string,string[]>,其中第一列是键,列的其余部分作为值的数组。

例如:

Key = arr[0,0], Value = new string[2] {arr[0,1], arr[0,2]}.
Run Code Online (Sandbox Code Playgroud)

我知道ToDictionary但我不知道如何设置值部分。

arr.ToDictionary(x=>arr[x,0],x=>new string[2]{arr[x,1],arr[x,2]});
//This doesn't work!!!
Run Code Online (Sandbox Code Playgroud)

我该如何正确设置?

c# arrays dictionary todictionary

6
推荐指数
2
解决办法
3577
查看次数

Linq ToDictionary 不会将类隐式转换为接口

我有以下代码

public class TestAdaptor
{
    private interface ITargetClass
    {
        Guid Id { get; }

        string Name { get; }
    }

    private class MyTargetClass : ITargetClass
    {
        public Guid Id { get; private set; }

        public string Name { get; private set; }

        public MyTargetClass(MySourceClass source)
        {
        }
    }

    private class MySourceClass
    {
        public Guid Id { get; set; }

        public string Name { get; set; }
    }

    private Dictionary<Guid, IEnumerable<ITargetClass>> ConvertItems(Dictionary<Guid, IEnumerable<MySourceClass>> source)
    {
        return source.ToDictionary(kvp => kvp.Key, kvp => …
Run Code Online (Sandbox Code Playgroud)

c# linq todictionary

5
推荐指数
1
解决办法
1644
查看次数