字符串的平均值或最大值

时间:2012-03-07 01:10:45

标签: c# linq linq-to-objects

说我有以下值

{ "Great", "Good", "Ok", "Poor", "Sucks" }

我有一个问题列表,其中包含答案。

我如何使用linq将其计算到对象?对于整数,我会这样做:

var q = (from g in questions select g.Answer).Max();select g.Answer).Avg();

我如何使用字符串来处理此问题,不是整数

7 个答案:

答案 0 :(得分:3)

您可以将“回答”值及其值放入词典中:

var answers = new Dictionary<string, int>();
answers.Add("Great", 5);
answers.Add("Good", 4);
answers.Add("Ok", 3);
answers.Add("Poor", 2);
answers.Add("Sucks", 1);

var q = questions.Select(q => answers[q.Answer]).Max();

答案 1 :(得分:2)

你能告诉我“很棒”&gt; “糟透了”或“很棒”&lt; “糟透了”?

我认为这取决于独立的业务,如果我是你,我会定义一个枚举来管理它。如下所示

Enum Sample
{
   Great = 1, 
   Good, 
   Ok,
   Poor, 
   Sucks 
}

然后你可以在你的代码中进行比较。

而且,如果您只需要按照索引比较列表,可以尝试这种方式。

        var data = new List<string>(){ "Great", "Good", "Ok", "Poor", "Sucks" };
        var result = data.Select((v, i) => new { Index = i, Value = v });

然后你可以用自己的逻辑完成它。

<强>更新

如果您只需要获取最大长度字符串,则可以尝试这种方式。

        var answers = new string[]{ "Grt", "Grt", "Good", "Poor" };
        var result = answers.Aggregate((a, b) => a.Length >= b.Length ? a : b);

获取最频繁的值

        var answers = new string[]{ "Grt", "Grt", "Good", "Poor" };
        var result = answers.GroupBy(q => q)
                                .OrderByDescending(gp => gp.Count())
                                .Select(g => g.Key).FirstOrDefault();

获取多个值的最常用值

        var answers = new string[] { "Grt", "Grt", "Good", "Good","kk"};
        var results = from p in answers
                      group p by p into g
                      let max = answers.GroupBy(p => p).Select(p => p.Count()).Max()
                      where g.Count() == max
                      select g.Key;

答案 2 :(得分:1)

创建一个函数(甚至只是一个字典),将字符串值映射到整数,并在您的问题中使用查询。即以g.answer为输入调用此函数。

答案 3 :(得分:1)

  var answerKinds = new[] { "Great", "Good", "Ok", "Poor", "Sucks" };
  var answerKindRanks = answerKinds.Select((kind, rank) => new { kind, rank })
   .ToDictionary(pair => pair.kind, pair => pair.rank);

  var questions = new[]
  {
    new{Q = "bla-bla", Answer = "Great"},
    new{Q = "bla-bla", Answer = "Sucks"},
    new{Q = "bla-bla", Answer = "Poor"},
  };
  var averageAnswer = answerKinds[(int)Math.Round(questions.Select(g => answerKindRanks[g.Answer]).Average())];

答案 4 :(得分:1)

string[] answers = new[] { "Great", "Good", "Ok", "Poor", "Sucks" };

var coolestAnswer = answers[questions.Select(q => Array.IndexOf(answers, q.Answer)).Min()];
var averageAnswer = answers[(int)questions.Select(q => Array.IndexOf(answers, q.Answer)).Average()];

答案 5 :(得分:1)

我对问题(以及后续评论)的理解是,在对问题的一系列回答中,您希望找到最常见的答案。请尝试以下方法:

class Question
{
    public string Answer;
}

static void Main(string[] args)
{
    var questions = new Question[] {
        new Question() { Answer = "Great" },
        new Question() { Answer = "Good" },
        new Question() { Answer = "Poor" },
        new Question() { Answer = "Good" },
        new Question() { Answer = "Great" },
        new Question() { Answer = "Sucks" }
    };
    var questionGroupsWithCount = from question in questions
                                  group question by question.Answer into questionGroup
                                  select new {
                                      QuestionCount = questionGroup.Count(),
                                      QuestionGroup = questionGroup
                                  };
    var mostCommonAnswerCount = questionGroupsWithCount.Max(item => item.QuestionCount);
    var mostCommonAnswers = from item in questionGroupsWithCount
                            where item.QuestionCount == mostCommonAnswerCount
                            select item.QuestionGroup.Key;

    foreach (var answer in mostCommonAnswers)
        Console.WriteLine("\"{0}\" was chosen {1:N0} time(s).", answer, mostCommonAnswerCount);
}

这是它正在做的事情:

  • Question的集合由相同的Answer组合在一起。计算每个组中Question的数量,并将其与组本身一起存储为匿名类型。
  • 检索最大组的大小。
  • 检索Key s,它们是Answer字段的值,具有最大尺寸的组。

请注意,可能有多个“最常见”的答案,这正确地处理了这个问题。上面的代码打印出来:

"Great" was chosen 2 time(s).
"Good" was chosen 2 time(s).

答案 6 :(得分:-2)

我在另一个帖子中找到了答案。

string[] answers = { "Great", "Great", "Good", "Poor" };
string text = answers.AsQueryable().Select(x => x).
    OrderByDescending(x => x.Count()).FirstOrDefault();