Linq select to new object

前端 未结 6 1830
攒了一身酷
攒了一身酷 2020-12-09 07:45

I have a linq query

var x = (from t in types select t).GroupBy(g =>g.Type)

which groups objects by their type, as a result I want to ha

相关标签:
6条回答
  • 2020-12-09 07:58
    var x = from t in types
            group t by t.Type into grouped
            select new { type = grouped.Key,
                         count = grouped.Count() };
    
    0 讨论(0)
  • 2020-12-09 08:07

    Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site

    var x = from t in types  group t by t.Type
             into grp    
             select new { type = grp.key, count = grp.Count() };
    

    forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary

        // fordictionary 
      var x = (from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() })
       .ToDictionary( t => t.type, t => t.count); 
    
       //for stringbuilder not sure for this 
      var x = from t in types  group t by t.Type
             into grp    
             select new { type = grp.key, count = grp.Count() };
      StringBuilder MyStringBuilder = new StringBuilder();
    
      foreach (var res in x)
      {
           //: is separator between to object
           MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
      }
      Console.WriteLine(MyStringBuilder.ToString());   
    
    0 讨论(0)
  • 2020-12-09 08:08

    The answers here got me close, but in 2016, I was able to write the following LINQ:

    List<ObjectType> objectList = similarTypeList.Select(o =>
        new ObjectType
        {
            PropertyOne = o.PropertyOne,
            PropertyTwo = o.PropertyTwo,
            PropertyThree = o.PropertyThree
        }).ToList();
    
    0 讨论(0)
  • 2020-12-09 08:18

    If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.

    var types = new[] {typeof(string), typeof(string), typeof(int)};
    var x = types
            .GroupBy(type => type)
            .ToDictionary(g => g.Key, g => g.Count());
    foreach (var kvp in x) {
        Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
    }
    Console.WriteLine("string has a count of {0}", x[typeof(string)]);
    
    0 讨论(0)
  • 2020-12-09 08:21

    This is a great article for syntax needed to create new objects from a LINQ query.

    But, if the assignments to fill in the fields of the object are anything more than simple assignments, for example, parsing strings to integers, and one of them fails, it is not possible to debug this. You can not create a breakpoint on any of the individual assignments.

    And if you move all the assignments to a subroutine, and return a new object from there, and attempt to set a breakpoint in that routine, you can set a breakpoint in that routine, but the breakpoint will never be triggered.

    So instead of:

    var query2 = from c in doc.Descendants("SuggestionItem")
                    select new SuggestionItem
                           { Phrase = c.Element("Phrase").Value
                             Blocked = bool.Parse(c.Element("Blocked").Value),
                             SeenCount = int.Parse(c.Element("SeenCount").Value)
                           };
    

    Or

    var query2 = from c in doc.Descendants("SuggestionItem")
                             select new SuggestionItem(c);
    

    I instead did this:

    List<SuggestionItem> retList = new List<SuggestionItem>();
    
    var query = from c in doc.Descendants("SuggestionItem") select c;
    
    foreach (XElement item in query)
    {
        SuggestionItem anItem = new SuggestionItem(item);
        retList.Add(anItem);
    }
    

    This allowed me to easily debug and figure out which assignment was failing. In this case, the XElement was missing a field I was parsing for to set in the SuggestionItem.

    I ran into these gotchas with Visual Studio 2017 while writing unit tests for a new library routine.

    0 讨论(0)
  • 2020-12-09 08:22

    All of the grouped objects, or all of the types? It sounds like you may just want:

    var query = types.GroupBy(t => t.Type)
                     .Select(g => new { Type = g.Key, Count = g.Count() });
    
    foreach (var result in query)
    {
        Console.WriteLine("{0}, {1}", result.Type, result.Count);
    }
    

    EDIT: If you want it in a dictionary, you can just use:

    var query = types.GroupBy(t => t.Type)
                     .ToDictionary(g => g.Key, g => g.Count());
    

    There's no need to select into pairs and then build the dictionary.

    0 讨论(0)
提交回复
热议问题