programing

LINQ를 사용하여 목록에서 중복을 계산하는 방법

nasanasas 2020. 10. 26. 08:04
반응형

LINQ를 사용하여 목록에서 중복을 계산하는 방법


항목 목록이 있습니다

  • John ID
  • Matt ID
  • John ID
  • 스콧 ID
  • Matt ID
  • John ID
  • Lucas ID

나는 그것들을 목록으로 다시 밀어 넣고 싶다. 이것은 또한 내가 가장 많은 중복 수를 기준으로 정렬하고 싶다는 것을 의미한다.

  • 존 ID 3
  • 매트 ID 2
  • 스콧 ID 1
  • Lucas ID 1

LINQ 및 C #을 사용하여이 작업을 수행하는 방법을 알려주십시오.

모두 감사합니다

코드를 보여주는 편집 2 :

    List<game> inventory = new List<game>();
    drinkingforDataContext db = new drinkingforDataContext();
    foreach (string item in tbTitle.Text.Split(' '))
    {

        List<game> getItems = (from dfg in db.drinkingfor_Games
                               where dfg.game_Name.Contains(tbTitle.Text)
                               select new game
                               {
                                   gameName = dfg.game_Name,
                                   gameID = Boomers.Utilities.Guids.Encoder.EncodeURLs(dfg.uid)
                               }).ToList<game>();

        for (int i = 0; i < getItems.Count(); i++)
        {
            inventory.Add(getItems[i]);
        }
    }

    var items = (from xx in inventory
                 group xx by xx into g
                 let count = g.Count()
                 orderby count descending
                 select new
                    {
                        Count = count,
                        gameName = g.Key.gameName,
                        gameID = g.Key.gameID
                    });

    lvRelatedGames.DataSource = items;
    lvRelatedGames.DataBind();

이 쿼리는 다음 결과를 표시합니다.

  • 1 안녕하세요 월드 타임
  • 1 안녕하세요 월드 타임
  • 1 Hello World.
  • 1 안녕하세요 월드 타임
  • 1 안녕하세요 월드 타임
  • 1 안녕하세요 월드 타임
  • 1 Hello World.
  • 1 안녕하세요 월드 타임

개수와 이름은 알려주지 만 게임 ID는 알려주지 않습니다 ....

다음과 같이 표시되어야합니다.

  • 6 헬로 월드 타임 234234
  • 2 안녕하세요. 23432432

"group by"+ "orderby"를 사용할 수 있습니다. 자세한 내용은 LINQ 101 을 참조하십시오.

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
        group x by x into g
        let count = g.Count()
        orderby count descending
        select new {Value = g.Key, Count = count};
foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

이 게시물에 대한 답변 (현재 삭제됨) :

일부 사용자 지정 개체 목록이있는 경우 사용자 지정 비교자를 사용 하거나 특정 속성별로 그룹화 해야 합니다.

또한 쿼리는 결과를 표시 할 수 없습니다. 더 나은 도움을 받으려면 완전한 코드를 보여주세요.

최신 업데이트를 기반으로 :

다음 코드 줄이 있습니다.

group xx by xx into g

xx는 사용자 지정 개체 시스템이므로 한 항목을 다른 항목과 비교하는 방법을 알지 못합니다. 이미 작성했듯이 컴파일러를 안내하고 개체 비교에 사용할 일부 속성을 제공하거나 사용자 지정 비교자를 제공해야합니다. 다음은 그 예입니다.

Foo.Name 을 키로 사용합니다. 즉, 개체는 Name 속성의 값을 기준으로 그룹화됩니다 .

There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.

//Using extension methods
var q = list.GroupBy(x => x.Name)
            .Select(x => new {Count = x.Count(), 
                              Name = x.Key, 
                              ID = x.First().ID})
            .OrderByDescending(x => x.Count);

//Using LINQ
var q = from x in list
        group x by x.Name into g
        let count = g.Count()
        orderby count descending
        select new {Name = g.Key, Count = count, ID = g.First().ID};

foreach (var x in q)
{
    Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

You can also do Dictionary:

 var list = new List<string> { "a", "b", "a", "c", "a", "b" };
 var result = list.GroupBy(x => x)
            .ToDictionary(y=>y.Key, y=>y.Count())
            .OrderByDescending(z => z.Value);

 foreach (var x in result)
        {
            Console.WriteLine("Value: " + x.Key + " Count: " + x.Value);
        }

The other solutions use GroupBy. GroupBy is slow (it holds all the elements in memory) so I wrote my own method CountBy:

public static Dictionary<TKey,int> CountBy<TSource,TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
{
    var countsByKey = new Dictionary<TKey,int>();
    foreach(var x in source)
    {
        var key = keySelector(x);
        if (!countsByKey.ContainsKey(key))
            countsByKey[key] = 0;
        countsByKey[key] += 1;
    }
    return countsByKey;
}

Here is the complete programme please check this

static void Main(string[] args)
{
    List<string> li = new List<string>();
    li.Add("Ram");
    li.Add("shyam");
    li.Add("Ram");
    li.Add("Kumar");
    li.Add("Kumar");

    var x = from obj in li group obj by obj into g select new { Name = g.Key, Duplicatecount = g.Count() };
    foreach(var m in x)
    {
        Console.WriteLine(m.Name + "--" + m.Duplicatecount);
    }
    Console.ReadLine();
}        

참고URL : https://stackoverflow.com/questions/454601/how-to-count-duplicates-in-list-with-linq

반응형