C#LINQ Collection包含的地方

时间:2018-05-11 17:17:23

标签: c# linq linq-to-sql

我是LINQ的新手,我将这个例子放在一起,以获得艺术家集合中包含嘻哈或流行音乐类型的项目数。任何有关此示例查询的帮助都将不胜感激!

folder.GetStream()

4 个答案:

答案 0 :(得分:1)

完整的工作控制台应用示例:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleAppTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var artists = new List<Artist>();
            artists.Add(new Artist { Name = "Pearl Jam", Genre = "ROCK" });
            artists.Add(new Artist { Name = "Beyonce", Genre = "POP" });
            if (HasNonRockArtists(artists)) Console.WriteLine("The list contains non-rock artists.");
            Console.ReadLine();
        }

        private static string[] genres = new string[] { "HIP HOP", "POP" };
        private static bool HasNonRockArtists(List<Artist> artists)
        {
            return artists.Any(a => genres.Contains(a.Genre));
        }
        public class Artist
        {
            public string Name { get; set; }
            public string Genre { get; set; }
        }
    }
}

答案 1 :(得分:0)

使它成为单线且更模块化的!

private static bool HasArtistByGenres(IEnumerable<Artist> artists, IEnumerable<string> genres) => artists.Any(a => genres.Contains(a.genre));

如果你不喜欢一个衬垫:

private static bool HasArtistByGenres(IEnumerable<Arist> artists, IEnumerable<string> genres)
{
    return artists.Any(a => a.genres.Contains(a.genre);
}

如果您更喜欢SQL语法更多的语法:

private static bool HasArtistByGenres(IEnumerable<Arist> artists, IEnumerable<string> genres)
{
    return (from a in Artists where genres.Contains(a.genre) select a).Any();
}

答案 2 :(得分:0)

private bool HasNonRockArtists()
{
   var genres = new List<string> { "HIP HOP", "POP" };
   return Artists.Any(artist => genres.Contains(artist.Genre));
}

答案 3 :(得分:-2)

您可以使用Contains方法但不像您那样。

您已将元素发送到Contains方法

var nonRockArtistsCount =  (from a in Artists 
                            where genres.Contains(a.Genre)
                            select a).Count();