匿名类型的ToDictionary

时间:2015-05-07 15:14:04

标签: c# linq anonymous-types

我正在尝试模仿已在我正在处理的代码库中创建的函数。第一个函数有效,但是当我尝试修改它以在字典中使用字符串时它不起作用。我得到System.Linq.Enumerable + WhereSelectEnumerableIterator 2[<>f__AnonymousType3 2 [System.Int32,System.String],System.String]作为注释的值。我知道第一个是使用平均值,这是一个聚合但我无法弄清楚如何将注释聚合为字符串。

public static Dictionary<int, double> getRatingAverages(string EventID)
        {
        List<tbMultipurposeVertical> allMain = DynamicData.Vertical.getRecords(EventID, appcode, -2).ToList();

        Dictionary<int, double> ratings;

        using (FBCDBDataContext db = new FBCDBDataContext())
            {
            ratings = db.tbMultipurposeVerticals.Where(v => v.eventid == EventID & v.appcode == "ratinglabel" & v.label == "Rater")
                .Select(v => new
                {
                    AbstractID = v.parent,
                    Rating = int.Parse(db.tbMultipurposeVerticals.First(r => r.parent == v.id & r.label == "Rating").value)
                })
                .GroupBy(r => r.AbstractID).ToDictionary(k => k.Key, v => v.Select(r => r.Rating).Average());
            }


        return ratings;
        }


    public static Dictionary<int, string> getRatingComments(string EventID)
    {
        List<tbMultipurposeVertical> allMain = DynamicData.Vertical.getRecords(EventID, appcode, -2).ToList();

        Dictionary<int, string> comments;

        using (FBCDBDataContext db = new FBCDBDataContext())
        {
            comments = db.tbMultipurposeVerticals.Where(v => v.eventid == EventID & v.appcode == "ratinglabel" & v.label == "Rater")
                .Select(v => new 
                {
                    AbstractID = v.parent,
                    Comment = db.tbMultipurposeVerticals.First(r => r.parent == v.id & r.label == "Comment").ToString()

                })
                .GroupBy(r => r.AbstractID).ToDictionary(k => k.Key, v => v.Select(r => r.Comment).ToString());
        }


        return comments;
    }

1 个答案:

答案 0 :(得分:0)

在第一种方法中,您将获取评级的平均值(聚合方法)。对于第二种方法,您现在将其视为单个注释。 由于.GroupBy()

,它没有给你你期望的东西

正如Steve Greene建议的那样,您可以获得第一条评论(v.First().ToString()v.FirstOrDefault().ToString()),或者如果在您的申请中有意义,您可以考虑连接评论(v.Concat()

否则,您可能希望将字典设为Dictionary<int, List<string>>