Skip to main content
 首页 » 编程设计

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

2024年02月06日11虾米哥

如何获取(或过滤)具有相同 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 或具有相同 artistID 且 userID = 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));