English 中文(简体)
Linq 选择新对象
原标题:Linq select to new object

我有一个Linq 查询

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

将对象按其类型分组,结果我要有包含所有组合对象及其计数的单一新对象。类似 :

type1, 30    
type2, 43    
type3, 72

更清晰:组合结果应归在一个对象中,而不是每个项目类型的对象

最佳回答

读取:101 LINQ 样本 ,该样本 < a href='"http://code.msdn.microsoft.com/LINQ-to-DataSets-grouping-c62703ea' rel=“无随从 noreferr'>LINQ -群集操作员 ,来自微软MSDN网站

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

对于单个对象,请使用 StringBuilder 并附加,或将其转换为字典形式:

    // 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());   
问题回答

但2016年, 我写了以下LINQ:

List<ObjectType> objectList = similarTypeList.Select(o =>
    new ObjectType
    {
        PropertyOne = o.PropertyOne,
        PropertyTwo = o.PropertyTwo,
        PropertyThree = o.PropertyThree
    }).ToList();

组合的所有 < em> 对象 < / em > 或所有 < em > 类型 < / em >? 听起来你可能想要 :

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);
}

如果您在字典中想要 < em> , 您可以只使用 :

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

不需要选择成对,而 然后 构建字典。

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

如果您想要对每种类型进行搜索以获得频率,您就需要将查点转换成字典。

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)]);

这是用于从 LINQ 查询中创建新对象所需的语法的伟大文章 。

但是,如果在对象字段中填充任务比简单的任务要简单得多,例如,将字符串对整数进行剖析,而其中一项失败,则无法调试这一点。在任何单个任务上无法创建断点。

如果您将所有任务移到子例程, 从那里返回一个新的对象, 并试图在常规中设置断点, 您可以在常规中设置断点, 但断点永远不会被触发 。

而不是:

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)
                       };

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

我却这样做:

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);
}

这让我可以很容易地调试并找出哪个任务失败了。 在这种情况下, XElement 丢失了我在建议项目中解释的字段 。

我在2017年与视觉工作室碰见了这些热门节目,同时为新的图书馆例行程序编写单位测试。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签