c# - 如何在列表中查找属性具有特定值或存在具有该值的相关项目的所有项目?

标签 c# linq list

如何获取(或过滤)具有相同 userID 和 artistID 的记录的列表

这是我的评分对象

public class Rating
{
    public int userID { get; set; }
    public int artistID { get; set; }
    public int rating { get; set; }
}

这是我的数据

Rating rate1 = new Rating { artistID = 1, userID = 101, rating = 2 };
Rating rate2 = new Rating { artistID = 1, userID = 102, rating = 4 };
Rating rate3 = new Rating { artistID = 2, userID = 101, rating = 3 };
Rating rate4 = new Rating { artistID = 2, userID = 102, rating = 5 };
Rating rate5 = new Rating { artistID = 3, userID = 102, rating = 1 };

List<Rating> ratings = new List<Rating>(2);
ratings.Add(rate1);
ratings.Add(rate2);
ratings.Add(rate3);
ratings.Add(rate4);
ratings.Add(rate5);

如果有ara记录输出: 其中 userID = 101,并且 其中(用户 ID 为 101 的艺术家 ID)

我想要的输出示例:

artistID    userID      rating
1           101         2
1           102         4
2           101         3
2           102         5

我还想要 1, 102, 4 因为这个 artistID 有另一个评级,用户 ID 是 101。这同样适用于 2, 102, 5

更新 如果您想包括所有记录,其中有另一条记录具有不同的用户但同一艺术家(来自@Tim Schmelter 的引述)。您可以在更新 版本中找到@Tim Schmelter 的答案。

例如,如果您将 rate5 更改为 Rating rate5 = new Rating { artistID = 3, userID = 101, rating = 1 }; 并添加新对象 rate6 Rating rate6 = new评分 { artistID = 3, userID = 102, rating = 1 };

它会产生结果:

artistID    userID      rating
1           101         2
1           102         4
2           101         3
2           102         5
3           101         1
3           102         1

因为 userID-101 评分的 artistID 也被 userid-102 评分 您可以在@Tim Schmelter 的回答中找到答案。

最佳答案

因此,您想要所有 userID 为 101 或具有相同 artistIDuserID = 101 的评级?您可以在 Where 中使用 Any:

var query = ratings.Where(r =>  r.userID  == 101 || 
              ratings.Any(rr => rr.userID == 101 && r.artistID == rr.artistID));

这类似于sql中的相关子查询。

测试:

foreach (Rating r in query)
    Console.WriteLine("artistID = {0}, userID = {1}, rating = {2}"
                   , r.artistID, r.userID, r.rating);

结果:

artistID = 1, userID = 101, rating = 2
artistID = 1, userID = 102, rating = 4
artistID = 2, userID = 101, rating = 3
artistID = 2, userID = 102, rating = 5

更新 “我想要所有包含不同用户但同一艺术家的另一条记录的记录”

现在很明显,您想要这个:

var query = ratings
    .Where(r => ratings
        .Any(rr => r.artistID == rr.artistID && rr.userID != r.userID));

关于c# - 如何在列表中查找属性具有特定值或存在具有该值的相关项目的所有项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25643131/

相关文章:

c# - IEnumerable<T> 跳过无限序列

c# - Asp .Net Core 中的访问被声明授权拒绝

c# - Watin 嵌入到 winform 应用程序中

c# - EF核心: Using ID as Primary key and foreign key at same time

c# - 我如何将一个简单的表达式附加到 IQueryable

c# - 如何在 NHibernate Linq 查询中执行不区分大小写的字符串?

Python - 字典未正确更新

c# - C# 中是否有任何方法或方式可以在 LIFO 的基础上添加 List<T> 中的项目?

c# - Visual Studio C++ 和 C# 的键盘快捷键

python - 如何将两个列表中的每个元素与其他列表中的每个元素进行比较,然后将结果合并到一个字符串中