Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Newbie Linq Clarifications Request C#

Discussion in 'Scripting' started by esitoinatteso, Oct 1, 2014.

  1. esitoinatteso

    esitoinatteso

    Joined:
    Sep 23, 2013
    Posts:
    26
    Hi all!
    I've managed to solve a problem with a simple solution and since I think it is related with Linq stuff I'd like to hear from you some clarifications...

    So, I have a list in one of my scripts, it's a List<int> called lAdeck.
    I'm using this List as a shuffle bag, so many items in it represent the same int... they are " copies" to tweak probabilities.
    Just because, yesterday I decided to " unwrap" it and see what's inside it.
    Specifically, I wanted to see how many copies of int 085 there were.

    What follows is what I've done.
    It worked like a charm, returning the number I expected, thus confirming both that what I've done is right and that my list is populated accordingly to my demands.

    Thing is... what is it that I've done exactly?
    Is it a Linq?

    And if not... then what's a Linq and how would one use it?
    Do I " need" it for this particular case?
    Because I tried a lot to make .FindAll(); work but I couldn't!

    Here's the code:

    Code (CSharp):
    1.         List<int> list = new List<int>();
    2.         int x = 085;
    3.         for(int i=0;i<lAdeck.Count;i++){
    4.             if(lAdeck[i] == x){
    5.                 list.Add(i);
    6.             }
    7.         }
    8.         Debug.Log (list.Count);
    Thanks in advance for your replies!
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    No - that's just a for loop. Linq comes in 2 flavors - a SQL-like syntax that you can execute against an arbitrary collection and a library of extension methods typically extending IEnumerable<T> in the System.Linq namespace. For your case I would probably do this:
    Code (csharp):
    1.  
    2. int count = lAdeck.Where<int>(i => i == x).ToArray<int>().length;
    3.  
     
  3. KevinDamore

    KevinDamore

    Joined:
    Sep 6, 2012
    Posts:
    9
  4. esitoinatteso

    esitoinatteso

    Joined:
    Sep 23, 2013
    Posts:
    26
    Hey Kelso! The single line of code is really good stuff, I'm looking forward to master that conciseness, thanks for sharing!
    And many thanks Kevin, that link seems to summarize cleverly all the infos I was looking for about the topic, it's odd I missed that page during all the google resarches!