c#,列表,集合和itterators [英] c#, lists, collections and itterators

查看:104
本文介绍了c#,列表,集合和itterators的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



无论出于何种原因,我想拿一个类型对象的字典,用字符串键入。

然后我想要一个字符串列表,当由itterator访问而不是返回字符串时...返回字典中由字符串键入的对象..



例如。



字典''dct''包含...... {{i1,Mark},{ i2,Fred},{i3,Harry}}

列表''lst''包含{i2,i1,i3}



然后......



foreach(对象a in lst){

控制台。 WriteLine(a)

}



会产生结果...



Fred

马克

哈利



如何实现这一目标?



非常感谢您的帮助



8 ^)

Mark

Hi Guys,

For whatever reason, I''d like to hold a dictionary of type object, keyed by a string.
I''d then like to have a list of strings, that when accessed by an itterator instead of returning the string ... returns the object in the dictionary that is keyed by the string..

eg.

Dictionary ''dct'' contains ... { { "i1","Mark" },{ "i2", "Fred" }, { "i3", "Harry" } }
List ''lst'' contains { "i2", "i1", "i3" }

then ...

foreach( object a in lst ) {
Console.WriteLine( a )
}

would produce the result ...

Fred
Mark
Harry

How do I achieve this?

Many thanks in advance for your help

8^)
Mark

推荐答案

你可以有任何理由将东西存放在字典中。

但其余的让我很困惑:为什么会这样?



你有几个选择,喜欢这些( LinqPad [ ^ ]脚本,但你可以看到这个概念)



You can have any reason to store things in a dictionary.
But the rest is quite confusing to me: why exactly that way?

You have several options, like these (LinqPad[^] script, but you can see the concept)

Dictionary<string, string> dictionary = new Dictionary<string,string>() {{"i1","John"},{"i2","Paul"},{"i3","Gloria"}};
List<string> list = new List<string>() {"i1","i3"};

// Option A
foreach(string index in list)
{
    dictionary[index].Dump();
}

// Option B
(from index in list select dictionary[index]).Dump();

// Option C
(from index in list join element in dictionary on index equals element.Key select element.Value).Dump();

// Option D
foreach(var @object in dictionary.Where(element => list.Contains(element.Key)).Select(element => element.Value))
{
	@object.Dump();
}





但你也可以在这里找到其他一些选择:http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet [ ^ ]



这里有一个基于选项D的更简洁的解决方案,通过扩展方法提取查询:





But you can find some other options here too: http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet[^]

And here is a neater solution based on option D, by extracting the query in an extension method:

public static class DictionaryExtension
{
    public static IEnumerable<T> Filter<T> (this Dictionary<string, T> dictionary, List<string> list)
    {
        return dictionary.Where(element => list.Contains(element.Key)).Select(element => element.Value);
    }
}
....
foreach(var @object in dictionary.Filter&lt;string&gt;(list))
    {
        @object.Dump();
    }


你的例子

Your example of
foreach (object a in lst){
  Console.WriteLine( a )
}



从未实际引用感兴趣的词典。

我认为返回<$ c的(扩展)方法$ c> IEnumerable< T> 将封装您想要的内容:


never actually references the Dictionary of interest.
I think an (extension) method that returns IEnumerable<T> would encapsulate what you seem to want:

using System.Linq;
public static class ExtensionMethod
{
  public static IEnumerable<Tvalue> SubSet<Tkey, Tvalue>(this Dictionary<Tkey, Tvalue> dict, IEnumerable<Tkey> inner, Tvalue notFoundValue = default(Tvalue))
  {
    if (inner == null)
      throw new ArgumentNullException("inner");
    return inner.Select(item => {
      Tvalue val;
      if (!dict.TryGetValue(item, out val))
      {
        val = notFoundValue;
      }
      return val;
    });
  }
}



请注意,如果找不到列表中的密钥,我提供了一种指定返回值的方法在字典中。

所以你会使用它:


Notice that I''ve provided a way to specify the value to be returned if the key from the list is not found in the Dictionary.
So you would use this like:

const string NotFound = "NotFound";            // could be string.Empty, etc.
foreach (var a in dict.SubSet(lst, NotFound)){ // the notFoundValue is optional
  Console.WriteLine( a )
}


根据你上面的评论,我会在没有LINQ的情况下重做:

Based on your comments above, I''ll redo this without LINQ:
public static class ExtensionMethods
{
  public static IEnumerable<Tvalue> SubSet<Tkey, Tvalue>(this Dictionary<Tkey, Tvalue> dict, IEnumerable<Tkey> inner, Tvalue notFoundValue = default(Tvalue))
  {
    if (dict == null)
      throw new ArgumentNullException("dict");
    if (inner == null)
      throw new ArgumentNullException("inner");
    foreach (Tkey item in inner)
    {
      Tvalue val;
      if (!dict.TryGetValue(item, out val))
      {
        val = notFoundValue;
      }
      yield return val;
    });
  }

  public static IEnumerable<Tvalue> SubSet<Tkey, Tvalue>(this Dictionary<Tkey, Tvalue> dict, IEnumerable<Tkey> inner)
  {
    return SubSet(dict, inner, default(Tvalue));
  }
}





此(及之前的解决方案)未经测试应该工作!;)。 (甚至没有编译。警告经纪人!


这篇关于c#,列表,集合和itterators的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆