【问题标题】:Comma separated values from SQL, getting distinct values and their count逗号分隔 SQL 中的值,获取不同的值及其计数
【发布时间】:2017-12-22 15:22:17
【问题描述】:

我有这个问题,我在SQL table 中有一个column。这些值采用comma separated 格式。

例如:

 1)   facebook,google,just giving, news letter, in-store
 2)   facebook,google,just giving
 3)   just giving
 4)   facebook
 5)   google
 6)   in-store,email
 7)   email,facebook

现在我想查询该表并在列表中获取此值,其中列表包含不同的值及其计数。

例如:

1) facebook - 10 
2) email - 20
3) in-store -5
and so on....

有没有办法使用 LINQ 来实现这一点?

注意:我可以在 LIST 变量上使用 LINQ 运算符,因为我的数据源是 'entries' 不支持 LINQ(内置于 .NET 2.0)

        var results = new List<string>();
        var builder = new StringBuilder();

        foreach (var entry in entries.Cast<MWCompetitionsEntry>().Where(entry => entry.HowFound != null))
        {
              builder.Append(entry.HowFound).Append(",");
        }

        results.Add(builder.ToString());

我得到的结果

facebook,email,in-store,google,in-store,newsletter,facebook,email,facebok

编辑:

现在,我可以处理results 变量。我不知道如何从该变量及其计数中获取唯一值。

请帮忙

回答

var values = new List<string>();
            var builder = new StringBuilder();
            var howFoundValues = new List<string>{"Email", "Facebook", "Twitter", "Leaflet", "Just Giving", "In-Store", "Other"};

            foreach (var entry in entries.Cast<MWCompetitionsEntry>().Where(entry => entry.HowFound != null))
            {
                  builder.Append(entry.HowFound).Append(",");
            }

            values.Add(builder.ToString());
            var result1 = values.SelectMany(l => l.Split(','))
                  .Where(howFoundValues.Contains) //will disregard any other items
                  .GroupBy(e => e)
                  .Select(e => String.Format("{0} - {1}",e.Key, e.Count()))
                  .ToList();

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    怎么样:

    var result = from word in entries.SelectMany(e => e.HowFound.Split(','))
                 group word by word into gr
                 select new {Entry = gr.Key, Count = gr.Count()};
    

    分组而不是区分可以让您获得计数。

    【讨论】:

    • 我的问题是我的数据源类是在 .NET 2.0 中构建的,它不支持任何 linq 运算符,所以我必须使用 foreach 并将字符串附加到某个变量中。
    • @patel.milanb 你用linq 标记了你的问题,所以得到linq 结果。
    • 不仅有标签,问题还特别说:how can i achieve this in LINQ.
    • 我可以在 LIST 变量上操作 linq,但不能在我的数据源(如条目然后获取不同的值。
    • @patel.milanb 只需将值读入字符串列表,这样您就有了一个列表变量,就像我的答案中的那个
    【解决方案2】:

    类似这样的:

    var groupedResults = results.SelectMany(v => v.Split(','))
                            .GroupBy(n => n)
                            .Select((item, index) => 
                                     new {
                                        name = String.Format("{0}) {1}", index+1, item.Key),
                                        count = item.Count()
                                     })
                            .ToList();
    
    1. 您需要按名称对元素进行分组。
    2. 在 LINQ to Objects 中,.Select() 运算符可以将 lambda 中的第二个参数作为索引,这可以帮助您附加编号。

    【讨论】:

    • 我的问题是我的数据源类是在 .NET 2.0 中构建的,它不支持任何 linq 运算符,所以我必须使用 foreach 并将字符串附加到某个变量中。但是它给了我'count = n.Count()'的错误我不知道为什么......它说无法解析符号Count()
    • 但是您使用的是SelectMany(),即LINQ运算符,我的代码有错误,刚刚更新。
    • 是的.. 但我可以在 LIST 上操作而不是在我的数据源上.. 像 entry.SelectMany ...
    • 好的,我得到的结果是 '1) System.Linq.Lookup`2+Grouping[System.String,System.String]'
    • 抱歉,我错过了将 .Key 添加到项目。更新了我的答案。
    【解决方案3】:
    var entries = new List<string>{"facebook,google,just giving, news letter, in-store",
     "facebook,google,just giving",
     "just giving", 
     "facebook",
     "google",
     "in-store,email",
     "email,facebook"};
    
    var result = entries
    .SelectMany (e => e.Split(','))
    .GroupBy (e => e).Select (g => string.Format("{0} - {1}", g.Count (), g.Key));
    
    result.Dump();
    

    结果

    4 - facebook 
    3 - google 
    3 - just giving 
    1 -  news letter 
    1 -  in-store 
    1 - in-store 
    2 - email 
    

    它首先拆分你的条目,然后按不同的字符串分组。

    如果您的数据像示例中一样包含前导和/或尾随空格,请考虑使用.GroupBy(e =&gt; e.Trim())

    【讨论】:

      【解决方案4】:

      试试这个

              Dictionary<string, int> valuesAndCount = new Dictionary<string, int>();
              foreach (var entry in entries) // entries is a collection of records from table
              {
                  string[] values = entry.Split(',');
                  foreach (var value in values)
                  {
                      if (!valuesAndCount.ContainsKey(value))
                      {
                          valuesAndCount.Add(value, 0);
                      }
                      valuesAndCount[value] = valuesAndCount[value] + 1;
                  }
              }
      
      
              //Then you'llhave your distinct values and thei count
              foreach (var key in valuesAndCount.Keys)
              {
                  Console.WriteLine("{0} {1}",key, valuesAndCount[key]);
              }
      

      那么字典应该包含您的不同值及其计数

      LINQ 版本

              IEnumerable<string> strings = entries
                  .ToList()
                  .SelectMany(e => e.Split(','))
                  .GroupBy(v => v)
                  .Select(str => string.Format("{0} {1}", str.Count(), str.Key));
      
      
              foreach (var p in strings)
              {
                  Console.WriteLine(p);
              }      
      

      【讨论】:

      • 我可以使用此方法查看值及其计数...但是有什么方法可以在此使用 LINQ
      猜你喜欢
      • 2015-01-25
      • 2016-12-03
      • 2020-04-26
      • 2017-08-04
      • 2021-09-04
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 2013-04-15
      相关资源
      最近更新 更多