【问题标题】:How to get grouping result as a list from the enumerable list?如何从可枚举列表中获取分组结果作为列表?
【发布时间】:2016-05-21 12:30:52
【问题描述】:

如何从列表中获取唯一记录?

public class VinDecoded
{
    public string SquishVin {get;set;} = "";
    public string Year {get;set;} = "";
    public string Make {get;set;} = "";
}
var modelVinDecodeds = new List<VinDecoded>();

modelVinDecodeds.Add(new VinDecoded() {SquishVin="1234",Year="2007",Make="Ford"});
modelVinDecodeds.Add(new VinDecoded() {SquishVin="2233",Year="2010",Make="Chevy"});
modelVinDecodeds.Add(new VinDecoded() {SquishVin="2233",Year="2010",Make="GMC"});

在这种情况下,我想获得自定义的List&lt;VinDecoded&gt;(),只有“2233”的匹配 SquishVin。

这个我试过了,但不起作用。我得到了钥匙,没有名单。我只想要没有 List 的 List&lt;VinDecoded&gt;() 数据。

var modelCustomVinDecoded = modelVinDecodeds.GroupBy(x => x.SquishVin).ToList();

foreach(var v in modelCustomVinDecoded)
{
    if (v.Key != "0033")
    {
         FooSave(v.???);   //Where's the list coming from the v part?
    }
}

【问题讨论】:

  • 你想让 linq 中的 group by 正确吗?
  • 或者你只需​​要得到“2233”结果意味着,使用where条件
  • 我在上面更新了一个更好的例子,看看是否有帮助。
  • v in foreach(var v in modelCustomVinDecoded) 是 IEnumerable,因此您可以迭代或将其转换为列表 v.ToList()

标签: c# enumerable


【解决方案1】:

GroupBy(x =&gt; x.SquishVin) 将返回一个 IEnumerable&lt;IGrouping&lt;string, VinDecoded&gt;&gt;IGrouping&lt;string, VinDecoded&gt; 有一个名为 Key 的属性返回组中所有 VinDecoded 对象中的 SquishVinIGrouping&lt;string, VinDecoded&gt; 也是 IEnumerable&lt;VinDecode&gt;,因此您可以对其进行迭代或将其转换为列表。

你可以这样做:

var modelCustomVinDecoded = modelVinDecodeds.GroupBy(x => x.SquishVin).ToList();

foreach(var v in modelCustomVinDecoded)
{
    if (v.Key != "0033")
    {
        FooSave(v.ToList());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多