복붙노트

[SQL] 문 "에서"SQL의 LINQ 버전

SQL

문 "에서"SQL의 LINQ 버전

나는 간단한 "항목 태그"스키마의 일환으로 다음과 같은 3 개 테이블이 :

== 아이템 ==

== 태그 ==

== == TagMap

나는 태그 목록과 일치하는 항목을 돌아 오게하기 위해 LINQ 쿼리를 작성하려면 (예를 들어 TagId = -2,3,4,7-). 내 응용 프로그램의 맥락에서, 항목의 예는 "컴퓨터 모니터", "드레스 셔츠", "기타"등이 될 것입니다 및 태그의 예는 "전자", "의류"것 등 내가 SQL로이를 일반적으로 것 IN 문.

해결법

  1. ==============================

    1.같은 뭔가

    같은 뭔가

    var TagIds = new int[] {12, 32, 42};
    
    var q = from map in Context.TagMaps 
            where TagIds.Contains(map.TagId)
            select map.Items;
    

    당신이 필요로해야한다. 이은에서를 생성합니다 (12, 32, 42) 절 (또는 더 구체적으로 내가 틀리지 않는 경우 매개 변수가 IN 절).

  2. ==============================

    2.주어진 항목의 배열 :

    주어진 항목의 배열 :

    var list = new int[] {2,3,4}
    

    사용하다:

    where list.Contains(tm.TagId)
    
  3. ==============================

    3.

    List<int> tagIds = new List<int>() {2, 3, 4, 7};
    int tagIdCount = tagIds.Count;
        //
    // Items that have any of the tags
    //  (any item may have any of the tags, not necessarily all of them
        //
    var ItemsAnyTags = db.Items
      .Where(item => item.TagMaps
        .Any(tm => tagIds.Contains(tm.TagId))
      );
    
        //
    // Items that have ALL of the tags
    //  (any item may have extra tags that are not mentioned).
        //
    var ItemIdsForAllTags = db.TagMap
      .Where(tm => tagIds.Contains(tm.TagId))
      .GroupBy(tm => tm.ItemId)
      .Where(g => g.Count() == tagIdCount)
      .Select(g => g.Key);
        //
    var ItemsWithAllTags = db.Items
      .Where(item => ItemsIdsForAllTags.Contains(item.ItemId));
    
    //runs just one query against the database
    List<Item> result = ItemsWithAllTags.ToList();
    
  4. ==============================

    4.당신은 간단하게 사용할 수 있습니다

    당신은 간단하게 사용할 수 있습니다

    var TagIds = {12, 32, 42}
    var prod =entities.TagMaps.Where(tagmaps=> TagIds .Contains(tagmaps.TagId));
    
  5. ==============================

    5.

    string[] names = {"John", "Cassandra", "Sarah"};
    
    var results = (from n in db.Names
                   where names.Contains(n.Name)
                   select n).ToList();
    
  6. ==============================

    6.당신은 ") (IN"확장 메서드를 만들 수 있습니다

    당신은 ") (IN"확장 메서드를 만들 수 있습니다

    public static class Extension
    {
        public static bool IN(this object anyObject, params object[] list)
        { return list.Contains(anyObject); }
    }
    

    이처럼 사용할 수

    var q = from map in Context.TagMaps 
            where map.TagId.IN(2, 3, 4, 7)
            select map.Items;
    

    아니면 그냥 인라인 array.Contains () 표기법을 사용 :

    var q = from map in Context.TagMaps 
            where new[]{2, 3, 4, 7}.Contains(map.TagId)
            select map.Items;
    
  7. from https://stackoverflow.com/questions/896123/linq-version-of-sql-in-statement by cc-by-sa and MIT license