C# LINQ获取列表中所有项的乘积

3

我有一个整数ID列表,其中的人共享令牌。我试图获取每对朋友ID号码的乘积。因此,朋友ID号码2和4将导致8等。

 var FriendsWhoShareTheMostTokens = FriendsWithTheirSharedTokensAmount.Select(x => new
            {
               FriendIdA = x.FriendTo.FriendID,
               FriendIdB  = x.FriendFor.FriendID,
               SharedCountNumber = x.SharedCount
            })
            .Where(x => x.SharedCountNumber == FriendsWithTheirSharedTokensAmount.Max(y => y.SharedCount))
            .ToList();

// need some code here** 
foreach (var pairOffriendsWhoSharetheMostTokens in FriendsWhoShareTheMostTokens)
{  

}

我可以用Linq来完成这个任务吗?或者有什么更好的方法来完成它?
2个回答

2

Edit

The answer is simple

 var ProductofGreatestTokenSharers = FriendsWhoShareTheMostTokens.Select(x => new
            {
                ProductOfIds = x.FriendIdA * x.FriendIdB
            }
        );

1

很难理解您在示例中想要实现什么。

但是,如果您想要获取id和产品,并获得最高的SharedCountNumber,您可能只需要执行以下操作:

您可以尝试执行以下操作:

var someResult = someList.Select(x => new
                            {
                                FriendIdA = x.FriendTo.FriendID,
                                FriendIdB = x.FriendFor.FriendID,
                                SharedCountNumber = x.FriendTo.FriendID * x.FriendFor.FriendID    
                            }) // Projection
                          .OrderByDescending(x => x.SharedCountNumber) // order the list
                          .FirstOrDefault(); // get the first

if (someResult != null)
{
    Debug.WriteLine($"A : {someResult.FriendIdA}, B : {someResult.FriendIdB}, Product : {someResult.SharedCountNumber}");
}

这就是我一直在寻找的。 - Curious-programmer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接