从使用LINQ扩展的另一个字典创建字典

时间:2015-10-09 12:58:56

标签: c# dictionary

odometervalue.frame=CGRectOffset(odometervalue.frame,0, offsetYPosition);
        units.frame=CGRectOffset(units.frame,0, offsetYPosition);

我有返回public class FamilyAndSubForProduct { public string MainFamily { get; set; } public string Feature { get; set; } public string Group { get; set; } public List<string> Synonyms { get; set; } } 的函数,我需要创建一个字典。现在我只有这个:

List<FamilyAndSubForProduct>

我的新词典需要保存var newDict = myFamily.Select(x => new Dictionary<string, Dictionary<string,string>>() { { x.MainFamily, new Dictionary<string,string>() { {x.Synonyms.Where(y => y == x.Feature), x.Feature} } } }).ToDictionary(); 以及此MainFamily其他MainFamilyFeatures(如果有)

例如Synonyms有:

myFamily

结果我需要这样的词典:

{
    MainFamily = productfamily
    Feature = productfeature
    Group = ""
    Synonyms = null
},
{
    MainFamily = productfamily
    Feature = productfeature1
    Group = ""
    Synonyms = productfeature1synonym, productfeature1synonm2
}

我的公式不起作用,我想学习如何做到这一点。谢谢你的回复

1 个答案:

答案 0 :(得分:1)

您可以像这样使用LINQ:

var myFamily = new List<FamilyAndSubForProduct>
{
    new FamilyAndSubForProduct
    {
        MainFamily = "productfamily",
        Feature = "productfeature",
        Group = "",
        Synonyms = null
    },
    new FamilyAndSubForProduct
    {
        MainFamily = "productfamily",
        Feature = "productfeature1",
        Group = "",
        Synonyms = new List<string> { "productfeature1synonym", "productfeature1synonm2" }
    }
};
var dict = myFamily.GroupBy(f => f.MainFamily).ToDictionary(g => g.Key,
    g => g.SelectMany(f => 
        Enumerable.Repeat(new KeyValuePair<string, string>(f.Feature, f.Feature), 1)
        .Concat(f.Synonyms != null ?
            f.Synonyms.Select(s => new KeyValuePair<string, string>(s, f.Feature)) :
            Enumerable.Empty<KeyValuePair<string, string>>())
        ).ToDictionary(e => e.Key, e => e.Value)
);

它的作用是首先按MainFamily对记录进行分组以生成外部字典的密钥,然后对于组中的每个项目,它创建2个集合 - 一个单独{Feature Feature}项,Synonym}项以及Feature中每个项目的{Synonymsvar dict = myFamily.GroupBy(f => f.MainFamily).ToDictionary(g => g.Key, g => g .SelectMany(f => Enumerable.Repeat(f.Feature, 1).Concat(f.Synonyms ?? Enumerable.Empty<string>()) .ToDictionary(s => s, s => f.Feature))); }可选的第二项,将这两个项合并在一起并生成内部字典。

编辑:使用更短的

可以实现同样的目标
string path = @"c:\ppd" + g.ToString() + ".jpg";
        using (MemoryStream inputStream = new MemoryStream(image))
        {
            Image returnImage = Image.FromStream(inputStream);
            returnImage.Save(path, ImageFormat.Jpeg);
        }
相关问题