按字典值组对象列表

时间:2017-12-14 09:30:35

标签: c# list linq

我的对象列表如下所示

8 bytes alignment

我想根据' SampleXML'中的值对列表进行分组。例如它包含价格等价值。我想根据价格对List进行分组。

如何实现相同。我尝试下面的代码,但它只是按键分隔列表。我需要独特的记录。

public class test
{
  public int ID{ get; set; }
  public string Name { get; set; }
  public Dictionary<string, string> SampleXML { get; set; }
}

以上代码根据价格生成列表。例如如果有6个记录有3个不同的价格,则上面的代码返回3个结果,但该列表再次包含两个记录。

修改

如果价格为空白则需要在分组中忽略,即如果有3条记录并且所有没有价格,那么列表将包含3项(原样)。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

编辑:基于Vicky S编辑 仍然将结果作为测试列表:

List<test> list = new List<test>();
List<test> result = new List<test>();
result = list.GroupBy(x => x.SampleXML["Price"]).Select(g=>g.FirstOrDefault());

编辑:包含具有空价格值或没有价格键的SampleXML的测试。执行以下操作:

首先,我们需要将测试与&#34; No Price&#34;并将它们包括在我们的最终结果中,从具有&#34; Price&#34;将它们分组的价值。

 var emptyPrice = list.Where(l => !l.SampleXML.ContainsKey("Price") || l.SampleXML["Price"] == string.Empty).ToList();
 var withoutEmptyPrice = list.Where(l => l.SampleXML.ContainsKey("Price") && !string.IsNullOrEmpty(l.SampleXML["Price"]));

然后我们将用&#34; Price&#34;值作为我的第一个答案。

var resultWithEmptyPrice = withoutEmptyPrice.GroupBy(x => x.SampleXML["Price"]).Select(g => g.FirstOrDefault()).ToList();

最后,我们将添加&#34; No Price&#34;测试我们的结果。

resultWithEmptyPrice.AddRange(emptyPrice);