如何使用LINQ获取仅包含组中对象的列表?

huangapple go评论65阅读模式
英文:

How do I get a list with only the objects of the group(s) using LINQ?

问题

我只需要在宽度值为100的情况下获取分组对象的标题。在这个示例中,这将是列1的分组标题。一个包含两个标题的列表。

var result = title.GroupBy(c => c.Column).?
英文:

I have an objects table with columns and widths.

column (int) width (double)
0 100
0 105
1 100
1 100

I only need the group objects title where the width values are 100.
In the example, this would be the group title with column 1. A list with two titles.

var result = title.GroupBy(c => c.Column).?

答案1

得分: 3

var result = title
.GroupBy(c => c.Column)
.Where(g => g.All(t => t.Width == 100))
.SelectMany(g => g);

这是Dotnet Fiddle演示

英文:
var result = title
	.GroupBy(c => c.Column)
	.Where(g => g.All(t => t.Width == 100))
	.SelectMany(g => g);

Here is Dotnet Fiddle demo

答案2

得分: 0

我只需要所有值的宽度都等于100的组对象标题。你的对象只有一个'Column'和一个'Width'。或者你是指你的对象还有一个'Title'吗?

首先,一些定义,这样更容易谈论事情。

class MyObject
{
    public string Title {get; set;}
    public int Column {get; set;}
    public double Width {get; set;}
}

IEnumerable<MyObject> myObjects = ... // 你想要处理的集合

这样怎么样:

var result = myObjects.Where(obj => obj.Width == 100.0)
                      .Select(obj => obj.Title);

换句话说,从你的原始MyObjects序列中,只保留那些Width属性的值等于100.0的MyObjects。然后从剩下的每个MyObject中,只选择Title属性的值。

英文:

> I only need the group objects title where all values width are equal to 100.

I understand the part "where all values widht are equal to 100.0". I don't understand the "I only need the group objects title". Your objects have only a 'Column' and a 'Width'. Or do you mean that your objects also have a 'Title'?

First some definitions, this makes it easier to talk about things.

class MyObject
{
    public string Title {get; set;}
    public int Column {get; set;}
    public double Width {get; set;}
}

IEnumerable&lt;MyObject&gt; myObjects = ... // the collection that you want to process

How about this:

var result = myObjects.Where(object =&gt; object.Width == 100.0)
                      .Select(object =&gt; object.Title);

In words: from your original sequence of MyObjects in variable myObjects, keep only those MyObjects that have a value for property Width that equals 100.0. From each of the remaining MyObjects select only the value of property Title.

huangapple
  • 本文由 发表于 2023年7月31日 23:30:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76805095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定